es6.js 4.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073
  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. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. var finalVertexCode;
  143. this._loadVertexShaderAsync(vertexSource)
  144. .then(function (vertexCode) {
  145. return _this._processIncludesAsync(vertexCode);
  146. })
  147. .then(function (vertexCodeWithIncludes) {
  148. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  149. return _this._loadFragmentShaderAsync(fragmentSource);
  150. })
  151. .then(function (fragmentCode) {
  152. return _this._processIncludesAsync(fragmentCode);
  153. })
  154. .then(function (fragmentCodeWithIncludes) {
  155. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  156. if (baseName) {
  157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  159. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  160. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  161. }
  162. else {
  163. _this._vertexSourceCode = finalVertexCode;
  164. _this._fragmentSourceCode = migratedFragmentCode;
  165. }
  166. _this._prepareEffect();
  167. });
  168. }
  169. Object.defineProperty(Effect.prototype, "key", {
  170. get: function () {
  171. return this._key;
  172. },
  173. enumerable: true,
  174. configurable: true
  175. });
  176. // Properties
  177. Effect.prototype.isReady = function () {
  178. return this._isReady;
  179. };
  180. Effect.prototype.getEngine = function () {
  181. return this._engine;
  182. };
  183. Effect.prototype.getProgram = function () {
  184. return this._program;
  185. };
  186. Effect.prototype.getAttributesNames = function () {
  187. return this._attributesNames;
  188. };
  189. Effect.prototype.getAttributeLocation = function (index) {
  190. return this._attributes[index];
  191. };
  192. Effect.prototype.getAttributeLocationByName = function (name) {
  193. var index = this._attributesNames.indexOf(name);
  194. return this._attributes[index];
  195. };
  196. Effect.prototype.getAttributesCount = function () {
  197. return this._attributes.length;
  198. };
  199. Effect.prototype.getUniformIndex = function (uniformName) {
  200. return this._uniformsNames.indexOf(uniformName);
  201. };
  202. Effect.prototype.getUniform = function (uniformName) {
  203. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  204. };
  205. Effect.prototype.getSamplers = function () {
  206. return this._samplers;
  207. };
  208. Effect.prototype.getCompilationError = function () {
  209. return this._compilationError;
  210. };
  211. // Methods
  212. Effect.prototype.executeWhenCompiled = function (func) {
  213. if (this.isReady()) {
  214. func(this);
  215. return;
  216. }
  217. this.onCompileObservable.add(function (effect) {
  218. func(effect);
  219. });
  220. };
  221. /** @ignore */
  222. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  223. if (BABYLON.Tools.IsWindowObjectExist()) {
  224. // DOM element ?
  225. if (vertex instanceof HTMLElement) {
  226. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  227. return Promise.resolve(vertexCode);
  228. }
  229. }
  230. // Base64 encoded ?
  231. if (vertex.substr(0, 7) === "base64:") {
  232. var vertexBinary = window.atob(vertex.substr(7));
  233. return Promise.resolve(vertexBinary);
  234. }
  235. // Is in local store ?
  236. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  237. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  238. }
  239. var vertexShaderUrl;
  240. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  241. vertexShaderUrl = vertex;
  242. }
  243. else {
  244. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  245. }
  246. // Vertex shader
  247. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  248. };
  249. /** @ignore */
  250. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  251. if (BABYLON.Tools.IsWindowObjectExist()) {
  252. // DOM element ?
  253. if (fragment instanceof HTMLElement) {
  254. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  255. return Promise.resolve(fragmentCode);
  256. }
  257. }
  258. // Base64 encoded ?
  259. if (fragment.substr(0, 7) === "base64:") {
  260. var fragmentBinary = window.atob(fragment.substr(7));
  261. return Promise.resolve(fragmentBinary);
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  266. }
  267. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  268. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  269. }
  270. var fragmentShaderUrl;
  271. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  272. fragmentShaderUrl = fragment;
  273. }
  274. else {
  275. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  276. }
  277. // Fragment shader
  278. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  279. };
  280. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  281. // Rebuild shaders source code
  282. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  283. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  284. vertexCode = prefix + vertexCode;
  285. fragmentCode = prefix + fragmentCode;
  286. // Number lines of shaders source code
  287. var i = 2;
  288. var regex = /\n/gm;
  289. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  290. i = 2;
  291. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. // Dump shaders name and formatted source code
  293. if (this.name.vertexElement) {
  294. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  295. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  296. }
  297. else if (this.name.vertex) {
  298. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  299. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  300. }
  301. else {
  302. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  303. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  304. }
  305. };
  306. ;
  307. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  308. var preparedSourceCode = this._processPrecision(sourceCode);
  309. if (this._engine.webGLVersion == 1) {
  310. return preparedSourceCode;
  311. }
  312. // Already converted
  313. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  314. return preparedSourceCode.replace("#version 300 es", "");
  315. }
  316. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  317. // Remove extensions
  318. // #extension GL_OES_standard_derivatives : enable
  319. // #extension GL_EXT_shader_texture_lod : enable
  320. // #extension GL_EXT_frag_depth : enable
  321. // #extension GL_EXT_draw_buffers : require
  322. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  323. var result = preparedSourceCode.replace(regex, "");
  324. // Migrate to GLSL v300
  325. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  326. result = result.replace(/attribute[ \t]/g, "in ");
  327. result = result.replace(/[ \t]attribute/g, " in");
  328. if (isFragment) {
  329. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  330. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  331. result = result.replace(/texture2D\s*\(/g, "texture(");
  332. result = result.replace(/textureCube\s*\(/g, "texture(");
  333. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  334. result = result.replace(/gl_FragColor/g, "glFragColor");
  335. result = result.replace(/gl_FragData/g, "glFragData");
  336. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  337. }
  338. return result;
  339. };
  340. Effect.prototype._processIncludesAsync = function (sourceCode) {
  341. var _this = this;
  342. return new Promise(function (resolve, reject) {
  343. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  344. var match = regex.exec(sourceCode);
  345. var returnValue = sourceCode;
  346. while (match != null) {
  347. var includeFile = match[1];
  348. // Uniform declaration
  349. if (includeFile.indexOf("__decl__") !== -1) {
  350. includeFile = includeFile.replace(/__decl__/, "");
  351. if (_this._engine.supportsUniformBuffers) {
  352. includeFile = includeFile.replace(/Vertex/, "Ubo");
  353. includeFile = includeFile.replace(/Fragment/, "Ubo");
  354. }
  355. includeFile = includeFile + "Declaration";
  356. }
  357. if (Effect.IncludesShadersStore[includeFile]) {
  358. // Substitution
  359. var includeContent = Effect.IncludesShadersStore[includeFile];
  360. if (match[2]) {
  361. var splits = match[3].split(",");
  362. for (var index = 0; index < splits.length; index += 2) {
  363. var source = new RegExp(splits[index], "g");
  364. var dest = splits[index + 1];
  365. includeContent = includeContent.replace(source, dest);
  366. }
  367. }
  368. if (match[4]) {
  369. var indexString = match[5];
  370. if (indexString.indexOf("..") !== -1) {
  371. var indexSplits = indexString.split("..");
  372. var minIndex = parseInt(indexSplits[0]);
  373. var maxIndex = parseInt(indexSplits[1]);
  374. var sourceIncludeContent = includeContent.slice(0);
  375. includeContent = "";
  376. if (isNaN(maxIndex)) {
  377. maxIndex = _this._indexParameters[indexSplits[1]];
  378. }
  379. for (var i = minIndex; i < maxIndex; i++) {
  380. if (!_this._engine.supportsUniformBuffers) {
  381. // Ubo replacement
  382. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  383. return p1 + "{X}";
  384. });
  385. }
  386. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  387. }
  388. }
  389. else {
  390. if (!_this._engine.supportsUniformBuffers) {
  391. // Ubo replacement
  392. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  393. return p1 + "{X}";
  394. });
  395. }
  396. includeContent = includeContent.replace(/\{X\}/g, indexString);
  397. }
  398. }
  399. // Replace
  400. returnValue = returnValue.replace(match[0], includeContent);
  401. }
  402. else {
  403. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  404. _this._engine._loadFileAsync(includeShaderUrl)
  405. .then(function (fileContent) {
  406. Effect.IncludesShadersStore[includeFile] = fileContent;
  407. return _this._processIncludesAsync(returnValue);
  408. })
  409. .then(function (returnValue) {
  410. resolve(returnValue);
  411. });
  412. return;
  413. }
  414. match = regex.exec(sourceCode);
  415. }
  416. resolve(returnValue);
  417. });
  418. };
  419. Effect.prototype._processPrecision = function (source) {
  420. if (source.indexOf("precision highp float") === -1) {
  421. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  422. source = "precision mediump float;\n" + source;
  423. }
  424. else {
  425. source = "precision highp float;\n" + source;
  426. }
  427. }
  428. else {
  429. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  430. source = source.replace("precision highp float", "precision mediump float");
  431. }
  432. }
  433. return source;
  434. };
  435. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  436. var _this = this;
  437. this._isReady = false;
  438. this._vertexSourceCodeOverride = vertexSourceCode;
  439. this._fragmentSourceCodeOverride = fragmentSourceCode;
  440. this.onError = function (effect, error) {
  441. if (onError) {
  442. onError(error);
  443. }
  444. };
  445. this.onCompiled = function () {
  446. var scenes = _this.getEngine().scenes;
  447. for (var i = 0; i < scenes.length; i++) {
  448. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  449. }
  450. if (onCompiled) {
  451. onCompiled(_this._program);
  452. }
  453. };
  454. this._fallbacks = null;
  455. this._prepareEffect();
  456. };
  457. Effect.prototype.getSpecificUniformLocations = function (names) {
  458. var engine = this._engine;
  459. return engine.getUniforms(this._program, names);
  460. };
  461. Effect.prototype._prepareEffect = function () {
  462. var attributesNames = this._attributesNames;
  463. var defines = this.defines;
  464. var fallbacks = this._fallbacks;
  465. this._valueCache = {};
  466. var previousProgram = this._program;
  467. try {
  468. var engine = this._engine;
  469. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  470. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  471. }
  472. else {
  473. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  474. }
  475. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  476. if (engine.supportsUniformBuffers) {
  477. for (var name in this._uniformBuffersNames) {
  478. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  479. }
  480. }
  481. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  482. this._attributes = engine.getAttributes(this._program, attributesNames);
  483. var index;
  484. for (index = 0; index < this._samplers.length; index++) {
  485. var sampler = this.getUniform(this._samplers[index]);
  486. if (sampler == null) {
  487. this._samplers.splice(index, 1);
  488. index--;
  489. }
  490. }
  491. engine.bindSamplers(this);
  492. this._compilationError = "";
  493. this._isReady = true;
  494. if (this.onCompiled) {
  495. this.onCompiled(this);
  496. }
  497. this.onCompileObservable.notifyObservers(this);
  498. this.onCompileObservable.clear();
  499. // Unbind mesh reference in fallbacks
  500. if (this._fallbacks) {
  501. this._fallbacks.unBindMesh();
  502. }
  503. if (previousProgram) {
  504. this.getEngine()._deleteProgram(previousProgram);
  505. }
  506. }
  507. catch (e) {
  508. this._compilationError = e.message;
  509. // Let's go through fallbacks then
  510. BABYLON.Tools.Error("Unable to compile effect:");
  511. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  512. return " " + uniform;
  513. }));
  514. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  515. return " " + attribute;
  516. }));
  517. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  518. BABYLON.Tools.Error("Error: " + this._compilationError);
  519. if (previousProgram) {
  520. this._program = previousProgram;
  521. this._isReady = true;
  522. if (this.onError) {
  523. this.onError(this, this._compilationError);
  524. }
  525. this.onErrorObservable.notifyObservers(this);
  526. }
  527. if (fallbacks && fallbacks.isMoreFallbacks) {
  528. BABYLON.Tools.Error("Trying next fallback.");
  529. this.defines = fallbacks.reduce(this.defines);
  530. this._prepareEffect();
  531. }
  532. else {
  533. if (this.onError) {
  534. this.onError(this, this._compilationError);
  535. }
  536. this.onErrorObservable.notifyObservers(this);
  537. this.onErrorObservable.clear();
  538. // Unbind mesh reference in fallbacks
  539. if (this._fallbacks) {
  540. this._fallbacks.unBindMesh();
  541. }
  542. }
  543. }
  544. };
  545. Object.defineProperty(Effect.prototype, "isSupported", {
  546. get: function () {
  547. return this._compilationError === "";
  548. },
  549. enumerable: true,
  550. configurable: true
  551. });
  552. Effect.prototype._bindTexture = function (channel, texture) {
  553. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  554. };
  555. Effect.prototype.setTexture = function (channel, texture) {
  556. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  557. };
  558. Effect.prototype.setTextureArray = function (channel, textures) {
  559. if (this._samplers.indexOf(channel + "Ex") === -1) {
  560. var initialPos = this._samplers.indexOf(channel);
  561. for (var index = 1; index < textures.length; index++) {
  562. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  563. }
  564. }
  565. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  566. };
  567. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  568. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  569. };
  570. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  571. var cache = this._valueCache[uniformName];
  572. var flag = matrix.updateFlag;
  573. if (cache !== undefined && cache === flag) {
  574. return false;
  575. }
  576. this._valueCache[uniformName] = flag;
  577. return true;
  578. };
  579. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  580. var cache = this._valueCache[uniformName];
  581. if (!cache) {
  582. cache = [x, y];
  583. this._valueCache[uniformName] = cache;
  584. return true;
  585. }
  586. var changed = false;
  587. if (cache[0] !== x) {
  588. cache[0] = x;
  589. changed = true;
  590. }
  591. if (cache[1] !== y) {
  592. cache[1] = y;
  593. changed = true;
  594. }
  595. return changed;
  596. };
  597. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  598. var cache = this._valueCache[uniformName];
  599. if (!cache) {
  600. cache = [x, y, z];
  601. this._valueCache[uniformName] = cache;
  602. return true;
  603. }
  604. var changed = false;
  605. if (cache[0] !== x) {
  606. cache[0] = x;
  607. changed = true;
  608. }
  609. if (cache[1] !== y) {
  610. cache[1] = y;
  611. changed = true;
  612. }
  613. if (cache[2] !== z) {
  614. cache[2] = z;
  615. changed = true;
  616. }
  617. return changed;
  618. };
  619. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  620. var cache = this._valueCache[uniformName];
  621. if (!cache) {
  622. cache = [x, y, z, w];
  623. this._valueCache[uniformName] = cache;
  624. return true;
  625. }
  626. var changed = false;
  627. if (cache[0] !== x) {
  628. cache[0] = x;
  629. changed = true;
  630. }
  631. if (cache[1] !== y) {
  632. cache[1] = y;
  633. changed = true;
  634. }
  635. if (cache[2] !== z) {
  636. cache[2] = z;
  637. changed = true;
  638. }
  639. if (cache[3] !== w) {
  640. cache[3] = w;
  641. changed = true;
  642. }
  643. return changed;
  644. };
  645. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  646. var bufferName = this._uniformBuffersNames[name];
  647. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  648. return;
  649. }
  650. Effect._baseCache[bufferName] = buffer;
  651. this._engine.bindUniformBufferBase(buffer, bufferName);
  652. };
  653. Effect.prototype.bindUniformBlock = function (blockName, index) {
  654. this._engine.bindUniformBlock(this._program, blockName, index);
  655. };
  656. Effect.prototype.setInt = function (uniformName, value) {
  657. var cache = this._valueCache[uniformName];
  658. if (cache !== undefined && cache === value)
  659. return this;
  660. this._valueCache[uniformName] = value;
  661. this._engine.setInt(this.getUniform(uniformName), value);
  662. return this;
  663. };
  664. Effect.prototype.setIntArray = function (uniformName, array) {
  665. this._valueCache[uniformName] = null;
  666. this._engine.setIntArray(this.getUniform(uniformName), array);
  667. return this;
  668. };
  669. Effect.prototype.setIntArray2 = function (uniformName, array) {
  670. this._valueCache[uniformName] = null;
  671. this._engine.setIntArray2(this.getUniform(uniformName), array);
  672. return this;
  673. };
  674. Effect.prototype.setIntArray3 = function (uniformName, array) {
  675. this._valueCache[uniformName] = null;
  676. this._engine.setIntArray3(this.getUniform(uniformName), array);
  677. return this;
  678. };
  679. Effect.prototype.setIntArray4 = function (uniformName, array) {
  680. this._valueCache[uniformName] = null;
  681. this._engine.setIntArray4(this.getUniform(uniformName), array);
  682. return this;
  683. };
  684. Effect.prototype.setFloatArray = function (uniformName, array) {
  685. this._valueCache[uniformName] = null;
  686. this._engine.setFloatArray(this.getUniform(uniformName), array);
  687. return this;
  688. };
  689. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  690. this._valueCache[uniformName] = null;
  691. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  692. return this;
  693. };
  694. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  695. this._valueCache[uniformName] = null;
  696. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  697. return this;
  698. };
  699. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  700. this._valueCache[uniformName] = null;
  701. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  702. return this;
  703. };
  704. Effect.prototype.setArray = function (uniformName, array) {
  705. this._valueCache[uniformName] = null;
  706. this._engine.setArray(this.getUniform(uniformName), array);
  707. return this;
  708. };
  709. Effect.prototype.setArray2 = function (uniformName, array) {
  710. this._valueCache[uniformName] = null;
  711. this._engine.setArray2(this.getUniform(uniformName), array);
  712. return this;
  713. };
  714. Effect.prototype.setArray3 = function (uniformName, array) {
  715. this._valueCache[uniformName] = null;
  716. this._engine.setArray3(this.getUniform(uniformName), array);
  717. return this;
  718. };
  719. Effect.prototype.setArray4 = function (uniformName, array) {
  720. this._valueCache[uniformName] = null;
  721. this._engine.setArray4(this.getUniform(uniformName), array);
  722. return this;
  723. };
  724. Effect.prototype.setMatrices = function (uniformName, matrices) {
  725. if (!matrices) {
  726. return this;
  727. }
  728. this._valueCache[uniformName] = null;
  729. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  730. return this;
  731. };
  732. Effect.prototype.setMatrix = function (uniformName, matrix) {
  733. if (this._cacheMatrix(uniformName, matrix)) {
  734. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  735. }
  736. return this;
  737. };
  738. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  739. this._valueCache[uniformName] = null;
  740. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  741. return this;
  742. };
  743. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  744. this._valueCache[uniformName] = null;
  745. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  746. return this;
  747. };
  748. Effect.prototype.setFloat = function (uniformName, value) {
  749. var cache = this._valueCache[uniformName];
  750. if (cache !== undefined && cache === value)
  751. return this;
  752. this._valueCache[uniformName] = value;
  753. this._engine.setFloat(this.getUniform(uniformName), value);
  754. return this;
  755. };
  756. Effect.prototype.setBool = function (uniformName, bool) {
  757. var cache = this._valueCache[uniformName];
  758. if (cache !== undefined && cache === bool)
  759. return this;
  760. this._valueCache[uniformName] = bool;
  761. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  762. return this;
  763. };
  764. Effect.prototype.setVector2 = function (uniformName, vector2) {
  765. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  766. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  767. }
  768. return this;
  769. };
  770. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  771. if (this._cacheFloat2(uniformName, x, y)) {
  772. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  773. }
  774. return this;
  775. };
  776. Effect.prototype.setVector3 = function (uniformName, vector3) {
  777. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  778. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  779. }
  780. return this;
  781. };
  782. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  783. if (this._cacheFloat3(uniformName, x, y, z)) {
  784. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  785. }
  786. return this;
  787. };
  788. Effect.prototype.setVector4 = function (uniformName, vector4) {
  789. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  790. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  791. }
  792. return this;
  793. };
  794. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  795. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  796. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  797. }
  798. return this;
  799. };
  800. Effect.prototype.setColor3 = function (uniformName, color3) {
  801. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  802. this._engine.setColor3(this.getUniform(uniformName), color3);
  803. }
  804. return this;
  805. };
  806. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  807. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  808. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  809. }
  810. return this;
  811. };
  812. Effect.ResetCache = function () {
  813. Effect._baseCache = {};
  814. };
  815. Effect._uniqueIdSeed = 0;
  816. Effect._baseCache = {};
  817. // Statics
  818. Effect.ShadersStore = {};
  819. Effect.IncludesShadersStore = {};
  820. return Effect;
  821. }());
  822. BABYLON.Effect = Effect;
  823. })(BABYLON || (BABYLON = {}));
  824. //# sourceMappingURL=babylon.effect.js.map
  825. //# sourceMappingURL=babylon.types.js.map
  826. var BABYLON;
  827. (function (BABYLON) {
  828. var KeyboardEventTypes = /** @class */ (function () {
  829. function KeyboardEventTypes() {
  830. }
  831. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  832. get: function () {
  833. return KeyboardEventTypes._KEYDOWN;
  834. },
  835. enumerable: true,
  836. configurable: true
  837. });
  838. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  839. get: function () {
  840. return KeyboardEventTypes._KEYUP;
  841. },
  842. enumerable: true,
  843. configurable: true
  844. });
  845. KeyboardEventTypes._KEYDOWN = 0x01;
  846. KeyboardEventTypes._KEYUP = 0x02;
  847. return KeyboardEventTypes;
  848. }());
  849. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  850. var KeyboardInfo = /** @class */ (function () {
  851. function KeyboardInfo(type, event) {
  852. this.type = type;
  853. this.event = event;
  854. }
  855. return KeyboardInfo;
  856. }());
  857. BABYLON.KeyboardInfo = KeyboardInfo;
  858. /**
  859. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  860. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  861. */
  862. var KeyboardInfoPre = /** @class */ (function (_super) {
  863. __extends(KeyboardInfoPre, _super);
  864. function KeyboardInfoPre(type, event) {
  865. var _this = _super.call(this, type, event) || this;
  866. _this.skipOnPointerObservable = false;
  867. return _this;
  868. }
  869. return KeyboardInfoPre;
  870. }(KeyboardInfo));
  871. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.keyboardEvents.js.map
  874. var BABYLON;
  875. (function (BABYLON) {
  876. var PointerEventTypes = /** @class */ (function () {
  877. function PointerEventTypes() {
  878. }
  879. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  880. get: function () {
  881. return PointerEventTypes._POINTERDOWN;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  887. get: function () {
  888. return PointerEventTypes._POINTERUP;
  889. },
  890. enumerable: true,
  891. configurable: true
  892. });
  893. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  894. get: function () {
  895. return PointerEventTypes._POINTERMOVE;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  901. get: function () {
  902. return PointerEventTypes._POINTERWHEEL;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  908. get: function () {
  909. return PointerEventTypes._POINTERPICK;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  915. get: function () {
  916. return PointerEventTypes._POINTERTAP;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  922. get: function () {
  923. return PointerEventTypes._POINTERDOUBLETAP;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. PointerEventTypes._POINTERDOWN = 0x01;
  929. PointerEventTypes._POINTERUP = 0x02;
  930. PointerEventTypes._POINTERMOVE = 0x04;
  931. PointerEventTypes._POINTERWHEEL = 0x08;
  932. PointerEventTypes._POINTERPICK = 0x10;
  933. PointerEventTypes._POINTERTAP = 0x20;
  934. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  935. return PointerEventTypes;
  936. }());
  937. BABYLON.PointerEventTypes = PointerEventTypes;
  938. var PointerInfoBase = /** @class */ (function () {
  939. function PointerInfoBase(type, event) {
  940. this.type = type;
  941. this.event = event;
  942. }
  943. return PointerInfoBase;
  944. }());
  945. BABYLON.PointerInfoBase = PointerInfoBase;
  946. /**
  947. * This class is used to store pointer related info for the onPrePointerObservable event.
  948. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  949. */
  950. var PointerInfoPre = /** @class */ (function (_super) {
  951. __extends(PointerInfoPre, _super);
  952. function PointerInfoPre(type, event, localX, localY) {
  953. var _this = _super.call(this, type, event) || this;
  954. _this.skipOnPointerObservable = false;
  955. _this.localPosition = new BABYLON.Vector2(localX, localY);
  956. return _this;
  957. }
  958. return PointerInfoPre;
  959. }(PointerInfoBase));
  960. BABYLON.PointerInfoPre = PointerInfoPre;
  961. /**
  962. * This type contains all the data related to a pointer event in Babylon.js.
  963. * 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.
  964. */
  965. var PointerInfo = /** @class */ (function (_super) {
  966. __extends(PointerInfo, _super);
  967. function PointerInfo(type, event, pickInfo) {
  968. var _this = _super.call(this, type, event) || this;
  969. _this.pickInfo = pickInfo;
  970. return _this;
  971. }
  972. return PointerInfo;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfo = PointerInfo;
  975. })(BABYLON || (BABYLON = {}));
  976. //# sourceMappingURL=babylon.pointerEvents.js.map
  977. var BABYLON;
  978. (function (BABYLON) {
  979. BABYLON.ToGammaSpace = 1 / 2.2;
  980. BABYLON.ToLinearSpace = 2.2;
  981. BABYLON.Epsilon = 0.001;
  982. var Color3 = /** @class */ (function () {
  983. /**
  984. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  985. */
  986. function Color3(r, g, b) {
  987. if (r === void 0) { r = 0; }
  988. if (g === void 0) { g = 0; }
  989. if (b === void 0) { b = 0; }
  990. this.r = r;
  991. this.g = g;
  992. this.b = b;
  993. }
  994. /**
  995. * Returns a string with the Color3 current values.
  996. */
  997. Color3.prototype.toString = function () {
  998. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  999. };
  1000. /**
  1001. * Returns the string "Color3".
  1002. */
  1003. Color3.prototype.getClassName = function () {
  1004. return "Color3";
  1005. };
  1006. /**
  1007. * Returns the Color3 hash code.
  1008. */
  1009. Color3.prototype.getHashCode = function () {
  1010. var hash = this.r || 0;
  1011. hash = (hash * 397) ^ (this.g || 0);
  1012. hash = (hash * 397) ^ (this.b || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1018. * Returns the Color3.
  1019. */
  1020. Color3.prototype.toArray = function (array, index) {
  1021. if (index === undefined) {
  1022. index = 0;
  1023. }
  1024. array[index] = this.r;
  1025. array[index + 1] = this.g;
  1026. array[index + 2] = this.b;
  1027. return this;
  1028. };
  1029. /**
  1030. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1031. */
  1032. Color3.prototype.toColor4 = function (alpha) {
  1033. if (alpha === void 0) { alpha = 1; }
  1034. return new Color4(this.r, this.g, this.b, alpha);
  1035. };
  1036. /**
  1037. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1038. */
  1039. Color3.prototype.asArray = function () {
  1040. var result = new Array();
  1041. this.toArray(result, 0);
  1042. return result;
  1043. };
  1044. /**
  1045. * Returns the luminance value (float).
  1046. */
  1047. Color3.prototype.toLuminance = function () {
  1048. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1049. };
  1050. /**
  1051. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1052. * Returns this new object.
  1053. */
  1054. Color3.prototype.multiply = function (otherColor) {
  1055. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1056. };
  1057. /**
  1058. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1059. * Returns the current Color3.
  1060. */
  1061. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1062. result.r = this.r * otherColor.r;
  1063. result.g = this.g * otherColor.g;
  1064. result.b = this.b * otherColor.b;
  1065. return this;
  1066. };
  1067. /**
  1068. * Boolean : True if the rgb values are equal to the passed ones.
  1069. */
  1070. Color3.prototype.equals = function (otherColor) {
  1071. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1072. };
  1073. /**
  1074. * Boolean : True if the rgb values are equal to the passed ones.
  1075. */
  1076. Color3.prototype.equalsFloats = function (r, g, b) {
  1077. return this.r === r && this.g === g && this.b === b;
  1078. };
  1079. /**
  1080. * Multiplies in place each rgb value by scale.
  1081. * Returns the updated Color3.
  1082. */
  1083. Color3.prototype.scale = function (scale) {
  1084. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1085. };
  1086. /**
  1087. * Multiplies the rgb values by scale and stores the result into "result".
  1088. * Returns the unmodified current Color3.
  1089. */
  1090. Color3.prototype.scaleToRef = function (scale, result) {
  1091. result.r = this.r * scale;
  1092. result.g = this.g * scale;
  1093. result.b = this.b * scale;
  1094. return this;
  1095. };
  1096. /**
  1097. * Clamps the rgb values by the min and max values and stores the result into "result".
  1098. * Returns the unmodified current Color3.
  1099. * @param min - minimum clamping value. Defaults to 0
  1100. * @param max - maximum clamping value. Defaults to 1
  1101. * @param result - color to store the result into.
  1102. * @returns - the original Color3
  1103. */
  1104. Color3.prototype.clampToRef = function (min, max, result) {
  1105. if (min === void 0) { min = 0; }
  1106. if (max === void 0) { max = 1; }
  1107. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1108. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1109. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1110. return this;
  1111. };
  1112. /**
  1113. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1114. */
  1115. Color3.prototype.add = function (otherColor) {
  1116. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1117. };
  1118. /**
  1119. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1120. * Returns the unmodified current Color3.
  1121. */
  1122. Color3.prototype.addToRef = function (otherColor, result) {
  1123. result.r = this.r + otherColor.r;
  1124. result.g = this.g + otherColor.g;
  1125. result.b = this.b + otherColor.b;
  1126. return this;
  1127. };
  1128. /**
  1129. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1130. */
  1131. Color3.prototype.subtract = function (otherColor) {
  1132. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1133. };
  1134. /**
  1135. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1136. * Returns the unmodified current Color3.
  1137. */
  1138. Color3.prototype.subtractToRef = function (otherColor, result) {
  1139. result.r = this.r - otherColor.r;
  1140. result.g = this.g - otherColor.g;
  1141. result.b = this.b - otherColor.b;
  1142. return this;
  1143. };
  1144. /**
  1145. * Returns a new Color3 copied the current one.
  1146. */
  1147. Color3.prototype.clone = function () {
  1148. return new Color3(this.r, this.g, this.b);
  1149. };
  1150. /**
  1151. * Copies the rgb values from the source in the current Color3.
  1152. * Returns the updated Color3.
  1153. */
  1154. Color3.prototype.copyFrom = function (source) {
  1155. this.r = source.r;
  1156. this.g = source.g;
  1157. this.b = source.b;
  1158. return this;
  1159. };
  1160. /**
  1161. * Updates the Color3 rgb values from the passed floats.
  1162. * Returns the Color3.
  1163. */
  1164. Color3.prototype.copyFromFloats = function (r, g, b) {
  1165. this.r = r;
  1166. this.g = g;
  1167. this.b = b;
  1168. return this;
  1169. };
  1170. /**
  1171. * Updates the Color3 rgb values from the passed floats.
  1172. * Returns the Color3.
  1173. */
  1174. Color3.prototype.set = function (r, g, b) {
  1175. return this.copyFromFloats(r, g, b);
  1176. };
  1177. /**
  1178. * Returns the Color3 hexadecimal code as a string.
  1179. */
  1180. Color3.prototype.toHexString = function () {
  1181. var intR = (this.r * 255) | 0;
  1182. var intG = (this.g * 255) | 0;
  1183. var intB = (this.b * 255) | 0;
  1184. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1185. };
  1186. /**
  1187. * Returns a new Color3 converted to linear space.
  1188. */
  1189. Color3.prototype.toLinearSpace = function () {
  1190. var convertedColor = new Color3();
  1191. this.toLinearSpaceToRef(convertedColor);
  1192. return convertedColor;
  1193. };
  1194. /**
  1195. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1196. * Returns the unmodified Color3.
  1197. */
  1198. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1199. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1200. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1201. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1202. return this;
  1203. };
  1204. /**
  1205. * Returns a new Color3 converted to gamma space.
  1206. */
  1207. Color3.prototype.toGammaSpace = function () {
  1208. var convertedColor = new Color3();
  1209. this.toGammaSpaceToRef(convertedColor);
  1210. return convertedColor;
  1211. };
  1212. /**
  1213. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1214. * Returns the unmodified Color3.
  1215. */
  1216. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1217. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1218. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1219. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1220. return this;
  1221. };
  1222. // Statics
  1223. /**
  1224. * Creates a new Color3 from the string containing valid hexadecimal values.
  1225. */
  1226. Color3.FromHexString = function (hex) {
  1227. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1228. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1229. return new Color3(0, 0, 0);
  1230. }
  1231. var r = parseInt(hex.substring(1, 3), 16);
  1232. var g = parseInt(hex.substring(3, 5), 16);
  1233. var b = parseInt(hex.substring(5, 7), 16);
  1234. return Color3.FromInts(r, g, b);
  1235. };
  1236. /**
  1237. * Creates a new Vector3 from the startind index of the passed array.
  1238. */
  1239. Color3.FromArray = function (array, offset) {
  1240. if (offset === void 0) { offset = 0; }
  1241. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1242. };
  1243. /**
  1244. * Creates a new Color3 from integer values ( < 256).
  1245. */
  1246. Color3.FromInts = function (r, g, b) {
  1247. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1248. };
  1249. /**
  1250. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1251. */
  1252. Color3.Lerp = function (start, end, amount) {
  1253. var r = start.r + ((end.r - start.r) * amount);
  1254. var g = start.g + ((end.g - start.g) * amount);
  1255. var b = start.b + ((end.b - start.b) * amount);
  1256. return new Color3(r, g, b);
  1257. };
  1258. Color3.Red = function () { return new Color3(1, 0, 0); };
  1259. Color3.Green = function () { return new Color3(0, 1, 0); };
  1260. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1261. Color3.Black = function () { return new Color3(0, 0, 0); };
  1262. Color3.White = function () { return new Color3(1, 1, 1); };
  1263. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1264. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1265. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1266. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1267. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1268. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1269. return Color3;
  1270. }());
  1271. BABYLON.Color3 = Color3;
  1272. var Color4 = /** @class */ (function () {
  1273. /**
  1274. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1275. */
  1276. function Color4(r, g, b, a) {
  1277. if (r === void 0) { r = 0; }
  1278. if (g === void 0) { g = 0; }
  1279. if (b === void 0) { b = 0; }
  1280. if (a === void 0) { a = 1; }
  1281. this.r = r;
  1282. this.g = g;
  1283. this.b = b;
  1284. this.a = a;
  1285. }
  1286. // Operators
  1287. /**
  1288. * Adds in place the passed Color4 values to the current Color4.
  1289. * Returns the updated Color4.
  1290. */
  1291. Color4.prototype.addInPlace = function (right) {
  1292. this.r += right.r;
  1293. this.g += right.g;
  1294. this.b += right.b;
  1295. this.a += right.a;
  1296. return this;
  1297. };
  1298. /**
  1299. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1300. */
  1301. Color4.prototype.asArray = function () {
  1302. var result = new Array();
  1303. this.toArray(result, 0);
  1304. return result;
  1305. };
  1306. /**
  1307. * Stores from the starting index in the passed array the Color4 successive values.
  1308. * Returns the Color4.
  1309. */
  1310. Color4.prototype.toArray = function (array, index) {
  1311. if (index === undefined) {
  1312. index = 0;
  1313. }
  1314. array[index] = this.r;
  1315. array[index + 1] = this.g;
  1316. array[index + 2] = this.b;
  1317. array[index + 3] = this.a;
  1318. return this;
  1319. };
  1320. /**
  1321. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1322. */
  1323. Color4.prototype.add = function (right) {
  1324. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1325. };
  1326. /**
  1327. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1328. */
  1329. Color4.prototype.subtract = function (right) {
  1330. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1331. };
  1332. /**
  1333. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1334. * Returns the Color4.
  1335. */
  1336. Color4.prototype.subtractToRef = function (right, result) {
  1337. result.r = this.r - right.r;
  1338. result.g = this.g - right.g;
  1339. result.b = this.b - right.b;
  1340. result.a = this.a - right.a;
  1341. return this;
  1342. };
  1343. /**
  1344. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1345. */
  1346. Color4.prototype.scale = function (scale) {
  1347. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1348. };
  1349. /**
  1350. * Multiplies the current Color4 values by scale and stores the result in "result".
  1351. * Returns the Color4.
  1352. */
  1353. Color4.prototype.scaleToRef = function (scale, result) {
  1354. result.r = this.r * scale;
  1355. result.g = this.g * scale;
  1356. result.b = this.b * scale;
  1357. result.a = this.a * scale;
  1358. return this;
  1359. };
  1360. /**
  1361. * Clamps the rgb values by the min and max values and stores the result into "result".
  1362. * Returns the unmodified current Color4.
  1363. * @param min - minimum clamping value. Defaults to 0
  1364. * @param max - maximum clamping value. Defaults to 1
  1365. * @param result - color to store the result into.
  1366. * @returns - the original Color4
  1367. */
  1368. Color4.prototype.clampToRef = function (min, max, result) {
  1369. if (min === void 0) { min = 0; }
  1370. if (max === void 0) { max = 1; }
  1371. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1372. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1373. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1374. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1375. return this;
  1376. };
  1377. /**
  1378. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1379. * @param color The Color4 (RGBA) value to multiply by
  1380. * @returns A new Color4.
  1381. */
  1382. Color4.prototype.multiply = function (color) {
  1383. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1384. };
  1385. /**
  1386. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1387. * @param color The Color4 (RGBA) value to multiply by
  1388. * @param result The Color4 (RGBA) to fill the result in
  1389. * @returns the result Color4.
  1390. */
  1391. Color4.prototype.multiplyToRef = function (color, result) {
  1392. result.r = this.r * color.r;
  1393. result.g = this.g * color.g;
  1394. result.b = this.b * color.b;
  1395. result.a = this.a * color.a;
  1396. return result;
  1397. };
  1398. /**
  1399. * Returns a string with the Color4 values.
  1400. */
  1401. Color4.prototype.toString = function () {
  1402. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1403. };
  1404. /**
  1405. * Returns the string "Color4"
  1406. */
  1407. Color4.prototype.getClassName = function () {
  1408. return "Color4";
  1409. };
  1410. /**
  1411. * Return the Color4 hash code as a number.
  1412. */
  1413. Color4.prototype.getHashCode = function () {
  1414. var hash = this.r || 0;
  1415. hash = (hash * 397) ^ (this.g || 0);
  1416. hash = (hash * 397) ^ (this.b || 0);
  1417. hash = (hash * 397) ^ (this.a || 0);
  1418. return hash;
  1419. };
  1420. /**
  1421. * Creates a new Color4 copied from the current one.
  1422. */
  1423. Color4.prototype.clone = function () {
  1424. return new Color4(this.r, this.g, this.b, this.a);
  1425. };
  1426. /**
  1427. * Copies the passed Color4 values into the current one.
  1428. * Returns the updated Color4.
  1429. */
  1430. Color4.prototype.copyFrom = function (source) {
  1431. this.r = source.r;
  1432. this.g = source.g;
  1433. this.b = source.b;
  1434. this.a = source.a;
  1435. return this;
  1436. };
  1437. /**
  1438. * Copies the passed float values into the current one.
  1439. * Returns the updated Color4.
  1440. */
  1441. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1442. this.r = r;
  1443. this.g = g;
  1444. this.b = b;
  1445. this.a = a;
  1446. return this;
  1447. };
  1448. /**
  1449. * Copies the passed float values into the current one.
  1450. * Returns the updated Color4.
  1451. */
  1452. Color4.prototype.set = function (r, g, b, a) {
  1453. return this.copyFromFloats(r, g, b, a);
  1454. };
  1455. /**
  1456. * Returns a string containing the hexadecimal Color4 code.
  1457. */
  1458. Color4.prototype.toHexString = function () {
  1459. var intR = (this.r * 255) | 0;
  1460. var intG = (this.g * 255) | 0;
  1461. var intB = (this.b * 255) | 0;
  1462. var intA = (this.a * 255) | 0;
  1463. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1464. };
  1465. /**
  1466. * Returns a new Color4 converted to linear space.
  1467. */
  1468. Color4.prototype.toLinearSpace = function () {
  1469. var convertedColor = new Color4();
  1470. this.toLinearSpaceToRef(convertedColor);
  1471. return convertedColor;
  1472. };
  1473. /**
  1474. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1475. * Returns the unmodified Color4.
  1476. */
  1477. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1478. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1479. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1480. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1481. convertedColor.a = this.a;
  1482. return this;
  1483. };
  1484. /**
  1485. * Returns a new Color4 converted to gamma space.
  1486. */
  1487. Color4.prototype.toGammaSpace = function () {
  1488. var convertedColor = new Color4();
  1489. this.toGammaSpaceToRef(convertedColor);
  1490. return convertedColor;
  1491. };
  1492. /**
  1493. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1494. * Returns the unmodified Color4.
  1495. */
  1496. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1497. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1498. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1499. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1500. convertedColor.a = this.a;
  1501. return this;
  1502. };
  1503. // Statics
  1504. /**
  1505. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1506. */
  1507. Color4.FromHexString = function (hex) {
  1508. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1509. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1510. return new Color4(0.0, 0.0, 0.0, 0.0);
  1511. }
  1512. var r = parseInt(hex.substring(1, 3), 16);
  1513. var g = parseInt(hex.substring(3, 5), 16);
  1514. var b = parseInt(hex.substring(5, 7), 16);
  1515. var a = parseInt(hex.substring(7, 9), 16);
  1516. return Color4.FromInts(r, g, b, a);
  1517. };
  1518. /**
  1519. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1520. */
  1521. Color4.Lerp = function (left, right, amount) {
  1522. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1523. Color4.LerpToRef(left, right, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1528. */
  1529. Color4.LerpToRef = function (left, right, amount, result) {
  1530. result.r = left.r + (right.r - left.r) * amount;
  1531. result.g = left.g + (right.g - left.g) * amount;
  1532. result.b = left.b + (right.b - left.b) * amount;
  1533. result.a = left.a + (right.a - left.a) * amount;
  1534. };
  1535. /**
  1536. * Creates a new Color4 from the starting index element of the passed array.
  1537. */
  1538. Color4.FromArray = function (array, offset) {
  1539. if (offset === void 0) { offset = 0; }
  1540. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1541. };
  1542. /**
  1543. * Creates a new Color4 from the passed integers ( < 256 ).
  1544. */
  1545. Color4.FromInts = function (r, g, b, a) {
  1546. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1547. };
  1548. Color4.CheckColors4 = function (colors, count) {
  1549. // Check if color3 was used
  1550. if (colors.length === count * 3) {
  1551. var colors4 = [];
  1552. for (var index = 0; index < colors.length; index += 3) {
  1553. var newIndex = (index / 3) * 4;
  1554. colors4[newIndex] = colors[index];
  1555. colors4[newIndex + 1] = colors[index + 1];
  1556. colors4[newIndex + 2] = colors[index + 2];
  1557. colors4[newIndex + 3] = 1.0;
  1558. }
  1559. return colors4;
  1560. }
  1561. return colors;
  1562. };
  1563. return Color4;
  1564. }());
  1565. BABYLON.Color4 = Color4;
  1566. var Vector2 = /** @class */ (function () {
  1567. /**
  1568. * Creates a new Vector2 from the passed x and y coordinates.
  1569. */
  1570. function Vector2(x, y) {
  1571. this.x = x;
  1572. this.y = y;
  1573. }
  1574. /**
  1575. * Returns a string with the Vector2 coordinates.
  1576. */
  1577. Vector2.prototype.toString = function () {
  1578. return "{X: " + this.x + " Y:" + this.y + "}";
  1579. };
  1580. /**
  1581. * Returns the string "Vector2"
  1582. */
  1583. Vector2.prototype.getClassName = function () {
  1584. return "Vector2";
  1585. };
  1586. /**
  1587. * Returns the Vector2 hash code as a number.
  1588. */
  1589. Vector2.prototype.getHashCode = function () {
  1590. var hash = this.x || 0;
  1591. hash = (hash * 397) ^ (this.y || 0);
  1592. return hash;
  1593. };
  1594. // Operators
  1595. /**
  1596. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1597. * Returns the Vector2.
  1598. */
  1599. Vector2.prototype.toArray = function (array, index) {
  1600. if (index === void 0) { index = 0; }
  1601. array[index] = this.x;
  1602. array[index + 1] = this.y;
  1603. return this;
  1604. };
  1605. /**
  1606. * Returns a new array with 2 elements : the Vector2 coordinates.
  1607. */
  1608. Vector2.prototype.asArray = function () {
  1609. var result = new Array();
  1610. this.toArray(result, 0);
  1611. return result;
  1612. };
  1613. /**
  1614. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1615. * Returns the updated Vector2.
  1616. */
  1617. Vector2.prototype.copyFrom = function (source) {
  1618. this.x = source.x;
  1619. this.y = source.y;
  1620. return this;
  1621. };
  1622. /**
  1623. * Sets the Vector2 coordinates with the passed floats.
  1624. * Returns the updated Vector2.
  1625. */
  1626. Vector2.prototype.copyFromFloats = function (x, y) {
  1627. this.x = x;
  1628. this.y = y;
  1629. return this;
  1630. };
  1631. /**
  1632. * Sets the Vector2 coordinates with the passed floats.
  1633. * Returns the updated Vector2.
  1634. */
  1635. Vector2.prototype.set = function (x, y) {
  1636. return this.copyFromFloats(x, y);
  1637. };
  1638. /**
  1639. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1640. */
  1641. Vector2.prototype.add = function (otherVector) {
  1642. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1643. };
  1644. /**
  1645. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1646. * Returns the Vector2.
  1647. */
  1648. Vector2.prototype.addToRef = function (otherVector, result) {
  1649. result.x = this.x + otherVector.x;
  1650. result.y = this.y + otherVector.y;
  1651. return this;
  1652. };
  1653. /**
  1654. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1655. * Returns the updated Vector2.
  1656. */
  1657. Vector2.prototype.addInPlace = function (otherVector) {
  1658. this.x += otherVector.x;
  1659. this.y += otherVector.y;
  1660. return this;
  1661. };
  1662. /**
  1663. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1664. */
  1665. Vector2.prototype.addVector3 = function (otherVector) {
  1666. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1667. };
  1668. /**
  1669. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1670. */
  1671. Vector2.prototype.subtract = function (otherVector) {
  1672. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1673. };
  1674. /**
  1675. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1676. * Returns the Vector2.
  1677. */
  1678. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1679. result.x = this.x - otherVector.x;
  1680. result.y = this.y - otherVector.y;
  1681. return this;
  1682. };
  1683. /**
  1684. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1685. * Returns the updated Vector2.
  1686. */
  1687. Vector2.prototype.subtractInPlace = function (otherVector) {
  1688. this.x -= otherVector.x;
  1689. this.y -= otherVector.y;
  1690. return this;
  1691. };
  1692. /**
  1693. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1694. * Returns the updated Vector2.
  1695. */
  1696. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1697. this.x *= otherVector.x;
  1698. this.y *= otherVector.y;
  1699. return this;
  1700. };
  1701. /**
  1702. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1703. */
  1704. Vector2.prototype.multiply = function (otherVector) {
  1705. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1706. };
  1707. /**
  1708. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1709. * Returns the Vector2.
  1710. */
  1711. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1712. result.x = this.x * otherVector.x;
  1713. result.y = this.y * otherVector.y;
  1714. return this;
  1715. };
  1716. /**
  1717. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1718. */
  1719. Vector2.prototype.multiplyByFloats = function (x, y) {
  1720. return new Vector2(this.x * x, this.y * y);
  1721. };
  1722. /**
  1723. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1724. */
  1725. Vector2.prototype.divide = function (otherVector) {
  1726. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1727. };
  1728. /**
  1729. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1730. * Returns the Vector2.
  1731. */
  1732. Vector2.prototype.divideToRef = function (otherVector, result) {
  1733. result.x = this.x / otherVector.x;
  1734. result.y = this.y / otherVector.y;
  1735. return this;
  1736. };
  1737. /**
  1738. * Divides the current Vector3 coordinates by the passed ones.
  1739. * Returns the updated Vector3.
  1740. */
  1741. Vector2.prototype.divideInPlace = function (otherVector) {
  1742. return this.divideToRef(otherVector, this);
  1743. };
  1744. /**
  1745. * Returns a new Vector2 with current Vector2 negated coordinates.
  1746. */
  1747. Vector2.prototype.negate = function () {
  1748. return new Vector2(-this.x, -this.y);
  1749. };
  1750. /**
  1751. * Multiply the Vector2 coordinates by scale.
  1752. * Returns the updated Vector2.
  1753. */
  1754. Vector2.prototype.scaleInPlace = function (scale) {
  1755. this.x *= scale;
  1756. this.y *= scale;
  1757. return this;
  1758. };
  1759. /**
  1760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1761. */
  1762. Vector2.prototype.scale = function (scale) {
  1763. return new Vector2(this.x * scale, this.y * scale);
  1764. };
  1765. /**
  1766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1767. */
  1768. Vector2.prototype.equals = function (otherVector) {
  1769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1770. };
  1771. /**
  1772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1773. */
  1774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1777. };
  1778. // Properties
  1779. /**
  1780. * Returns the vector length (float).
  1781. */
  1782. Vector2.prototype.length = function () {
  1783. return Math.sqrt(this.x * this.x + this.y * this.y);
  1784. };
  1785. /**
  1786. * Returns the vector squared length (float);
  1787. */
  1788. Vector2.prototype.lengthSquared = function () {
  1789. return (this.x * this.x + this.y * this.y);
  1790. };
  1791. // Methods
  1792. /**
  1793. * Normalize the vector.
  1794. * Returns the updated Vector2.
  1795. */
  1796. Vector2.prototype.normalize = function () {
  1797. var len = this.length();
  1798. if (len === 0)
  1799. return this;
  1800. var num = 1.0 / len;
  1801. this.x *= num;
  1802. this.y *= num;
  1803. return this;
  1804. };
  1805. /**
  1806. * Returns a new Vector2 copied from the Vector2.
  1807. */
  1808. Vector2.prototype.clone = function () {
  1809. return new Vector2(this.x, this.y);
  1810. };
  1811. // Statics
  1812. /**
  1813. * Returns a new Vector2(0, 0)
  1814. */
  1815. Vector2.Zero = function () {
  1816. return new Vector2(0, 0);
  1817. };
  1818. /**
  1819. * Returns a new Vector2(1, 1)
  1820. */
  1821. Vector2.One = function () {
  1822. return new Vector2(1, 1);
  1823. };
  1824. /**
  1825. * Returns a new Vector2 set from the passed index element of the passed array.
  1826. */
  1827. Vector2.FromArray = function (array, offset) {
  1828. if (offset === void 0) { offset = 0; }
  1829. return new Vector2(array[offset], array[offset + 1]);
  1830. };
  1831. /**
  1832. * Sets "result" from the passed index element of the passed array.
  1833. */
  1834. Vector2.FromArrayToRef = function (array, offset, result) {
  1835. result.x = array[offset];
  1836. result.y = array[offset + 1];
  1837. };
  1838. /**
  1839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1840. */
  1841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1842. var squared = amount * amount;
  1843. var cubed = amount * squared;
  1844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1850. return new Vector2(x, y);
  1851. };
  1852. /**
  1853. * 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".
  1854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1856. */
  1857. Vector2.Clamp = function (value, min, max) {
  1858. var x = value.x;
  1859. x = (x > max.x) ? max.x : x;
  1860. x = (x < min.x) ? min.x : x;
  1861. var y = value.y;
  1862. y = (y > max.y) ? max.y : y;
  1863. y = (y < min.y) ? min.y : y;
  1864. return new Vector2(x, y);
  1865. };
  1866. /**
  1867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1868. */
  1869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1870. var squared = amount * amount;
  1871. var cubed = amount * squared;
  1872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1874. var part3 = (cubed - (2.0 * squared)) + amount;
  1875. var part4 = cubed - squared;
  1876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1878. return new Vector2(x, y);
  1879. };
  1880. /**
  1881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1882. */
  1883. Vector2.Lerp = function (start, end, amount) {
  1884. var x = start.x + ((end.x - start.x) * amount);
  1885. var y = start.y + ((end.y - start.y) * amount);
  1886. return new Vector2(x, y);
  1887. };
  1888. /**
  1889. * Returns the dot product (float) of the vector "left" and the vector "right".
  1890. */
  1891. Vector2.Dot = function (left, right) {
  1892. return left.x * right.x + left.y * right.y;
  1893. };
  1894. /**
  1895. * Returns a new Vector2 equal to the normalized passed vector.
  1896. */
  1897. Vector2.Normalize = function (vector) {
  1898. var newVector = vector.clone();
  1899. newVector.normalize();
  1900. return newVector;
  1901. };
  1902. /**
  1903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1904. */
  1905. Vector2.Minimize = function (left, right) {
  1906. var x = (left.x < right.x) ? left.x : right.x;
  1907. var y = (left.y < right.y) ? left.y : right.y;
  1908. return new Vector2(x, y);
  1909. };
  1910. /**
  1911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1912. */
  1913. Vector2.Maximize = function (left, right) {
  1914. var x = (left.x > right.x) ? left.x : right.x;
  1915. var y = (left.y > right.y) ? left.y : right.y;
  1916. return new Vector2(x, y);
  1917. };
  1918. /**
  1919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1920. */
  1921. Vector2.Transform = function (vector, transformation) {
  1922. var r = Vector2.Zero();
  1923. Vector2.TransformToRef(vector, transformation, r);
  1924. return r;
  1925. };
  1926. /**
  1927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1928. */
  1929. Vector2.TransformToRef = function (vector, transformation, result) {
  1930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1932. result.x = x;
  1933. result.y = y;
  1934. };
  1935. /**
  1936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1937. */
  1938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1940. var sign = a < 0 ? -1 : 1;
  1941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1944. };
  1945. /**
  1946. * Returns the distance (float) between the vectors "value1" and "value2".
  1947. */
  1948. Vector2.Distance = function (value1, value2) {
  1949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1950. };
  1951. /**
  1952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1953. */
  1954. Vector2.DistanceSquared = function (value1, value2) {
  1955. var x = value1.x - value2.x;
  1956. var y = value1.y - value2.y;
  1957. return (x * x) + (y * y);
  1958. };
  1959. /**
  1960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1961. */
  1962. Vector2.Center = function (value1, value2) {
  1963. var center = value1.add(value2);
  1964. center.scaleInPlace(0.5);
  1965. return center;
  1966. };
  1967. /**
  1968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1969. */
  1970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1971. var l2 = Vector2.DistanceSquared(segA, segB);
  1972. if (l2 === 0.0) {
  1973. return Vector2.Distance(p, segA);
  1974. }
  1975. var v = segB.subtract(segA);
  1976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1977. var proj = segA.add(v.multiplyByFloats(t, t));
  1978. return Vector2.Distance(p, proj);
  1979. };
  1980. return Vector2;
  1981. }());
  1982. BABYLON.Vector2 = Vector2;
  1983. var Vector3 = /** @class */ (function () {
  1984. /**
  1985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1986. * A Vector3 is the main object used in 3D geometry.
  1987. * It can represent etiher the coordinates of a point the space, either a direction.
  1988. */
  1989. function Vector3(x, y, z) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. }
  1994. /**
  1995. * Returns a string with the Vector3 coordinates.
  1996. */
  1997. Vector3.prototype.toString = function () {
  1998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1999. };
  2000. /**
  2001. * Returns the string "Vector3"
  2002. */
  2003. Vector3.prototype.getClassName = function () {
  2004. return "Vector3";
  2005. };
  2006. /**
  2007. * Returns the Vector hash code.
  2008. */
  2009. Vector3.prototype.getHashCode = function () {
  2010. var hash = this.x || 0;
  2011. hash = (hash * 397) ^ (this.y || 0);
  2012. hash = (hash * 397) ^ (this.z || 0);
  2013. return hash;
  2014. };
  2015. // Operators
  2016. /**
  2017. * Returns a new array with three elements : the coordinates the Vector3.
  2018. */
  2019. Vector3.prototype.asArray = function () {
  2020. var result = [];
  2021. this.toArray(result, 0);
  2022. return result;
  2023. };
  2024. /**
  2025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2026. * Returns the Vector3.
  2027. */
  2028. Vector3.prototype.toArray = function (array, index) {
  2029. if (index === void 0) { index = 0; }
  2030. array[index] = this.x;
  2031. array[index + 1] = this.y;
  2032. array[index + 2] = this.z;
  2033. return this;
  2034. };
  2035. /**
  2036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2037. */
  2038. Vector3.prototype.toQuaternion = function () {
  2039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2044. var cosy = Math.cos(this.y * 0.5);
  2045. var siny = Math.sin(this.y * 0.5);
  2046. result.x = coszMinusx * siny;
  2047. result.y = -sinzMinusx * siny;
  2048. result.z = sinxPlusz * cosy;
  2049. result.w = cosxPlusz * cosy;
  2050. return result;
  2051. };
  2052. /**
  2053. * Adds the passed vector to the current Vector3.
  2054. * Returns the updated Vector3.
  2055. */
  2056. Vector3.prototype.addInPlace = function (otherVector) {
  2057. this.x += otherVector.x;
  2058. this.y += otherVector.y;
  2059. this.z += otherVector.z;
  2060. return this;
  2061. };
  2062. /**
  2063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2064. */
  2065. Vector3.prototype.add = function (otherVector) {
  2066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2067. };
  2068. /**
  2069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2070. * Returns the current Vector3.
  2071. */
  2072. Vector3.prototype.addToRef = function (otherVector, result) {
  2073. result.x = this.x + otherVector.x;
  2074. result.y = this.y + otherVector.y;
  2075. result.z = this.z + otherVector.z;
  2076. return this;
  2077. };
  2078. /**
  2079. * Subtract the passed vector from the current Vector3.
  2080. * Returns the updated Vector3.
  2081. */
  2082. Vector3.prototype.subtractInPlace = function (otherVector) {
  2083. this.x -= otherVector.x;
  2084. this.y -= otherVector.y;
  2085. this.z -= otherVector.z;
  2086. return this;
  2087. };
  2088. /**
  2089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2090. */
  2091. Vector3.prototype.subtract = function (otherVector) {
  2092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2093. };
  2094. /**
  2095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2096. * Returns the current Vector3.
  2097. */
  2098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2099. result.x = this.x - otherVector.x;
  2100. result.y = this.y - otherVector.y;
  2101. result.z = this.z - otherVector.z;
  2102. return this;
  2103. };
  2104. /**
  2105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2106. */
  2107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2108. return new Vector3(this.x - x, this.y - y, this.z - z);
  2109. };
  2110. /**
  2111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2112. * Returns the current Vector3.
  2113. */
  2114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2115. result.x = this.x - x;
  2116. result.y = this.y - y;
  2117. result.z = this.z - z;
  2118. return this;
  2119. };
  2120. /**
  2121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2122. */
  2123. Vector3.prototype.negate = function () {
  2124. return new Vector3(-this.x, -this.y, -this.z);
  2125. };
  2126. /**
  2127. * Multiplies the Vector3 coordinates by the float "scale".
  2128. * Returns the updated Vector3.
  2129. */
  2130. Vector3.prototype.scaleInPlace = function (scale) {
  2131. this.x *= scale;
  2132. this.y *= scale;
  2133. this.z *= scale;
  2134. return this;
  2135. };
  2136. /**
  2137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2138. */
  2139. Vector3.prototype.scale = function (scale) {
  2140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2141. };
  2142. /**
  2143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2144. * Returns the current Vector3.
  2145. */
  2146. Vector3.prototype.scaleToRef = function (scale, result) {
  2147. result.x = this.x * scale;
  2148. result.y = this.y * scale;
  2149. result.z = this.z * scale;
  2150. return this;
  2151. };
  2152. /**
  2153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2154. */
  2155. Vector3.prototype.equals = function (otherVector) {
  2156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2157. };
  2158. /**
  2159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2160. */
  2161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2163. 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);
  2164. };
  2165. /**
  2166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2167. */
  2168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2169. return this.x === x && this.y === y && this.z === z;
  2170. };
  2171. /**
  2172. * Muliplies the current Vector3 coordinates by the passed ones.
  2173. * Returns the updated Vector3.
  2174. */
  2175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2176. this.x *= otherVector.x;
  2177. this.y *= otherVector.y;
  2178. this.z *= otherVector.z;
  2179. return this;
  2180. };
  2181. /**
  2182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2183. */
  2184. Vector3.prototype.multiply = function (otherVector) {
  2185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2186. };
  2187. /**
  2188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2189. * Returns the current Vector3.
  2190. */
  2191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2192. result.x = this.x * otherVector.x;
  2193. result.y = this.y * otherVector.y;
  2194. result.z = this.z * otherVector.z;
  2195. return this;
  2196. };
  2197. /**
  2198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2199. */
  2200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2201. return new Vector3(this.x * x, this.y * y, this.z * z);
  2202. };
  2203. /**
  2204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2205. */
  2206. Vector3.prototype.divide = function (otherVector) {
  2207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2208. };
  2209. /**
  2210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2211. * Returns the current Vector3.
  2212. */
  2213. Vector3.prototype.divideToRef = function (otherVector, result) {
  2214. result.x = this.x / otherVector.x;
  2215. result.y = this.y / otherVector.y;
  2216. result.z = this.z / otherVector.z;
  2217. return this;
  2218. };
  2219. /**
  2220. * Divides the current Vector3 coordinates by the passed ones.
  2221. * Returns the updated Vector3.
  2222. */
  2223. Vector3.prototype.divideInPlace = function (otherVector) {
  2224. return this.divideToRef(otherVector, this);
  2225. };
  2226. /**
  2227. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2228. * Returns the updated Vector3.
  2229. */
  2230. Vector3.prototype.MinimizeInPlace = function (other) {
  2231. if (other.x < this.x)
  2232. this.x = other.x;
  2233. if (other.y < this.y)
  2234. this.y = other.y;
  2235. if (other.z < this.z)
  2236. this.z = other.z;
  2237. return this;
  2238. };
  2239. /**
  2240. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2241. * Returns the updated Vector3.
  2242. */
  2243. Vector3.prototype.MaximizeInPlace = function (other) {
  2244. if (other.x > this.x)
  2245. this.x = other.x;
  2246. if (other.y > this.y)
  2247. this.y = other.y;
  2248. if (other.z > this.z)
  2249. this.z = other.z;
  2250. return this;
  2251. };
  2252. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2253. /**
  2254. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2255. */
  2256. get: function () {
  2257. var absX = Math.abs(this.x);
  2258. var absY = Math.abs(this.y);
  2259. if (absX !== absY) {
  2260. return true;
  2261. }
  2262. var absZ = Math.abs(this.z);
  2263. if (absX !== absZ) {
  2264. return true;
  2265. }
  2266. if (absY !== absZ) {
  2267. return true;
  2268. }
  2269. return false;
  2270. },
  2271. enumerable: true,
  2272. configurable: true
  2273. });
  2274. // Properties
  2275. /**
  2276. * Returns the length of the Vector3 (float).
  2277. */
  2278. Vector3.prototype.length = function () {
  2279. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2280. };
  2281. /**
  2282. * Returns the squared length of the Vector3 (float).
  2283. */
  2284. Vector3.prototype.lengthSquared = function () {
  2285. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2286. };
  2287. /**
  2288. * Normalize the current Vector3.
  2289. * Returns the updated Vector3.
  2290. * /!\ In place operation.
  2291. */
  2292. Vector3.prototype.normalize = function () {
  2293. var len = this.length();
  2294. if (len === 0 || len === 1.0)
  2295. return this;
  2296. var num = 1.0 / len;
  2297. this.x *= num;
  2298. this.y *= num;
  2299. this.z *= num;
  2300. return this;
  2301. };
  2302. /**
  2303. * Normalize the current Vector3 to a new vector.
  2304. * @returns the new Vector3.
  2305. */
  2306. Vector3.prototype.normalizeToNew = function () {
  2307. var normalized = new Vector3(0, 0, 0);
  2308. this.normalizeToRef(normalized);
  2309. return normalized;
  2310. };
  2311. /**
  2312. * Normalize the current Vector3 to the reference.
  2313. * @param the reference to update.
  2314. * @returns the updated Vector3.
  2315. */
  2316. Vector3.prototype.normalizeToRef = function (reference) {
  2317. var len = this.length();
  2318. if (len === 0 || len === 1.0) {
  2319. reference.set(this.x, this.y, this.z);
  2320. return reference;
  2321. }
  2322. var scale = 1.0 / len;
  2323. this.scaleToRef(scale, reference);
  2324. return reference;
  2325. };
  2326. /**
  2327. * Returns a new Vector3 copied from the current Vector3.
  2328. */
  2329. Vector3.prototype.clone = function () {
  2330. return new Vector3(this.x, this.y, this.z);
  2331. };
  2332. /**
  2333. * Copies the passed vector coordinates to the current Vector3 ones.
  2334. * Returns the updated Vector3.
  2335. */
  2336. Vector3.prototype.copyFrom = function (source) {
  2337. this.x = source.x;
  2338. this.y = source.y;
  2339. this.z = source.z;
  2340. return this;
  2341. };
  2342. /**
  2343. * Copies the passed floats to the current Vector3 coordinates.
  2344. * Returns the updated Vector3.
  2345. */
  2346. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2347. this.x = x;
  2348. this.y = y;
  2349. this.z = z;
  2350. return this;
  2351. };
  2352. /**
  2353. * Copies the passed floats to the current Vector3 coordinates.
  2354. * Returns the updated Vector3.
  2355. */
  2356. Vector3.prototype.set = function (x, y, z) {
  2357. return this.copyFromFloats(x, y, z);
  2358. };
  2359. // Statics
  2360. /**
  2361. *
  2362. */
  2363. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2364. var d0 = Vector3.Dot(vector0, axis) - size;
  2365. var d1 = Vector3.Dot(vector1, axis) - size;
  2366. var s = d0 / (d0 - d1);
  2367. return s;
  2368. };
  2369. /**
  2370. * Get angle between two vectors.
  2371. * @param vector0 angle between vector0 and vector1
  2372. * @param vector1 angle between vector0 and vector1
  2373. * @param normal direction of the normal.
  2374. * @return the angle between vector0 and vector1.
  2375. */
  2376. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2377. var v0 = vector0.clone().normalize();
  2378. var v1 = vector1.clone().normalize();
  2379. var dot = Vector3.Dot(v0, v1);
  2380. var n = Vector3.Cross(v0, v1);
  2381. if (Vector3.Dot(n, normal) > 0) {
  2382. return Math.acos(dot);
  2383. }
  2384. return -Math.acos(dot);
  2385. };
  2386. /**
  2387. * Returns a new Vector3 set from the index "offset" of the passed array.
  2388. */
  2389. Vector3.FromArray = function (array, offset) {
  2390. if (!offset) {
  2391. offset = 0;
  2392. }
  2393. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2394. };
  2395. /**
  2396. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2397. * This function is deprecated. Use FromArray instead.
  2398. */
  2399. Vector3.FromFloatArray = function (array, offset) {
  2400. return Vector3.FromArray(array, offset);
  2401. };
  2402. /**
  2403. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2404. */
  2405. Vector3.FromArrayToRef = function (array, offset, result) {
  2406. result.x = array[offset];
  2407. result.y = array[offset + 1];
  2408. result.z = array[offset + 2];
  2409. };
  2410. /**
  2411. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2412. * This function is deprecated. Use FromArrayToRef instead.
  2413. */
  2414. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2415. return Vector3.FromArrayToRef(array, offset, result);
  2416. };
  2417. /**
  2418. * Sets the passed vector "result" with the passed floats.
  2419. */
  2420. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2421. result.x = x;
  2422. result.y = y;
  2423. result.z = z;
  2424. };
  2425. /**
  2426. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2427. */
  2428. Vector3.Zero = function () {
  2429. return new Vector3(0.0, 0.0, 0.0);
  2430. };
  2431. /**
  2432. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2433. */
  2434. Vector3.One = function () {
  2435. return new Vector3(1.0, 1.0, 1.0);
  2436. };
  2437. /**
  2438. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2439. */
  2440. Vector3.Up = function () {
  2441. return new Vector3(0.0, 1.0, 0.0);
  2442. };
  2443. /**
  2444. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2445. */
  2446. Vector3.Forward = function () {
  2447. return new Vector3(0.0, 0.0, 1.0);
  2448. };
  2449. /**
  2450. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2451. */
  2452. Vector3.Right = function () {
  2453. return new Vector3(1.0, 0.0, 0.0);
  2454. };
  2455. /**
  2456. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2457. */
  2458. Vector3.Left = function () {
  2459. return new Vector3(-1.0, 0.0, 0.0);
  2460. };
  2461. /**
  2462. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2463. * This method computes tranformed coordinates only, not transformed direction vectors.
  2464. */
  2465. Vector3.TransformCoordinates = function (vector, transformation) {
  2466. var result = Vector3.Zero();
  2467. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2468. return result;
  2469. };
  2470. /**
  2471. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2472. * This method computes tranformed coordinates only, not transformed direction vectors.
  2473. */
  2474. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2475. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2476. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2477. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2478. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2479. result.x = x / w;
  2480. result.y = y / w;
  2481. result.z = z / w;
  2482. };
  2483. /**
  2484. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2485. * This method computes tranformed coordinates only, not transformed direction vectors.
  2486. */
  2487. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2488. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2489. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2490. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2491. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2492. result.x = rx / rw;
  2493. result.y = ry / rw;
  2494. result.z = rz / rw;
  2495. };
  2496. /**
  2497. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2498. * This methods computes transformed normalized direction vectors only.
  2499. */
  2500. Vector3.TransformNormal = function (vector, transformation) {
  2501. var result = Vector3.Zero();
  2502. Vector3.TransformNormalToRef(vector, transformation, result);
  2503. return result;
  2504. };
  2505. /**
  2506. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2507. * This methods computes transformed normalized direction vectors only.
  2508. */
  2509. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2510. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2511. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2512. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2513. result.x = x;
  2514. result.y = y;
  2515. result.z = z;
  2516. };
  2517. /**
  2518. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2519. * This methods computes transformed normalized direction vectors only.
  2520. */
  2521. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2522. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2523. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2524. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2525. };
  2526. /**
  2527. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2528. */
  2529. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2530. var squared = amount * amount;
  2531. var cubed = amount * squared;
  2532. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2533. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2534. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2535. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2536. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2537. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2538. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2539. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2540. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2541. return new Vector3(x, y, z);
  2542. };
  2543. /**
  2544. * 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".
  2545. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2546. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2547. */
  2548. Vector3.Clamp = function (value, min, max) {
  2549. var x = value.x;
  2550. x = (x > max.x) ? max.x : x;
  2551. x = (x < min.x) ? min.x : x;
  2552. var y = value.y;
  2553. y = (y > max.y) ? max.y : y;
  2554. y = (y < min.y) ? min.y : y;
  2555. var z = value.z;
  2556. z = (z > max.z) ? max.z : z;
  2557. z = (z < min.z) ? min.z : z;
  2558. return new Vector3(x, y, z);
  2559. };
  2560. /**
  2561. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2562. */
  2563. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2564. var squared = amount * amount;
  2565. var cubed = amount * squared;
  2566. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2567. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2568. var part3 = (cubed - (2.0 * squared)) + amount;
  2569. var part4 = cubed - squared;
  2570. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2571. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2572. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2573. return new Vector3(x, y, z);
  2574. };
  2575. /**
  2576. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2577. */
  2578. Vector3.Lerp = function (start, end, amount) {
  2579. var result = new Vector3(0, 0, 0);
  2580. Vector3.LerpToRef(start, end, amount, result);
  2581. return result;
  2582. };
  2583. /**
  2584. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2585. */
  2586. Vector3.LerpToRef = function (start, end, amount, result) {
  2587. result.x = start.x + ((end.x - start.x) * amount);
  2588. result.y = start.y + ((end.y - start.y) * amount);
  2589. result.z = start.z + ((end.z - start.z) * amount);
  2590. };
  2591. /**
  2592. * Returns the dot product (float) between the vectors "left" and "right".
  2593. */
  2594. Vector3.Dot = function (left, right) {
  2595. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2596. };
  2597. /**
  2598. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2599. * The cross product is then orthogonal to both "left" and "right".
  2600. */
  2601. Vector3.Cross = function (left, right) {
  2602. var result = Vector3.Zero();
  2603. Vector3.CrossToRef(left, right, result);
  2604. return result;
  2605. };
  2606. /**
  2607. * Sets the passed vector "result" with the cross product of "left" and "right".
  2608. * The cross product is then orthogonal to both "left" and "right".
  2609. */
  2610. Vector3.CrossToRef = function (left, right, result) {
  2611. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2612. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2613. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2614. result.copyFrom(MathTmp.Vector3[0]);
  2615. };
  2616. /**
  2617. * Returns a new Vector3 as the normalization of the passed vector.
  2618. */
  2619. Vector3.Normalize = function (vector) {
  2620. var result = Vector3.Zero();
  2621. Vector3.NormalizeToRef(vector, result);
  2622. return result;
  2623. };
  2624. /**
  2625. * Sets the passed vector "result" with the normalization of the passed first vector.
  2626. */
  2627. Vector3.NormalizeToRef = function (vector, result) {
  2628. result.copyFrom(vector);
  2629. result.normalize();
  2630. };
  2631. Vector3.Project = function (vector, world, transform, viewport) {
  2632. var cw = viewport.width;
  2633. var ch = viewport.height;
  2634. var cx = viewport.x;
  2635. var cy = viewport.y;
  2636. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2637. 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);
  2638. var matrix = MathTmp.Matrix[0];
  2639. world.multiplyToRef(transform, matrix);
  2640. matrix.multiplyToRef(viewportMatrix, matrix);
  2641. return Vector3.TransformCoordinates(vector, matrix);
  2642. };
  2643. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2644. var matrix = MathTmp.Matrix[0];
  2645. world.multiplyToRef(transform, matrix);
  2646. matrix.invert();
  2647. source.x = source.x / viewportWidth * 2 - 1;
  2648. source.y = -(source.y / viewportHeight * 2 - 1);
  2649. var vector = Vector3.TransformCoordinates(source, matrix);
  2650. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2651. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2652. vector = vector.scale(1.0 / num);
  2653. }
  2654. return vector;
  2655. };
  2656. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2657. var result = Vector3.Zero();
  2658. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2659. return result;
  2660. };
  2661. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2662. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2663. };
  2664. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2665. var matrix = MathTmp.Matrix[0];
  2666. world.multiplyToRef(view, matrix);
  2667. matrix.multiplyToRef(projection, matrix);
  2668. matrix.invert();
  2669. var screenSource = MathTmp.Vector3[0];
  2670. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2671. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2672. screenSource.z = 2 * sourceZ - 1.0;
  2673. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2674. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2675. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2676. result.scaleInPlace(1.0 / num);
  2677. }
  2678. };
  2679. Vector3.Minimize = function (left, right) {
  2680. var min = left.clone();
  2681. min.MinimizeInPlace(right);
  2682. return min;
  2683. };
  2684. Vector3.Maximize = function (left, right) {
  2685. var max = left.clone();
  2686. max.MaximizeInPlace(right);
  2687. return max;
  2688. };
  2689. /**
  2690. * Returns the distance (float) between the vectors "value1" and "value2".
  2691. */
  2692. Vector3.Distance = function (value1, value2) {
  2693. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2694. };
  2695. /**
  2696. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2697. */
  2698. Vector3.DistanceSquared = function (value1, value2) {
  2699. var x = value1.x - value2.x;
  2700. var y = value1.y - value2.y;
  2701. var z = value1.z - value2.z;
  2702. return (x * x) + (y * y) + (z * z);
  2703. };
  2704. /**
  2705. * Returns a new Vector3 located at the center between "value1" and "value2".
  2706. */
  2707. Vector3.Center = function (value1, value2) {
  2708. var center = value1.add(value2);
  2709. center.scaleInPlace(0.5);
  2710. return center;
  2711. };
  2712. /**
  2713. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2714. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2715. * to something in order to rotate it from its local system to the given target system.
  2716. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2717. * Returns a new Vector3.
  2718. */
  2719. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2720. var rotation = Vector3.Zero();
  2721. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2722. return rotation;
  2723. };
  2724. /**
  2725. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2726. */
  2727. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2728. var quat = MathTmp.Quaternion[0];
  2729. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2730. quat.toEulerAnglesToRef(ref);
  2731. };
  2732. return Vector3;
  2733. }());
  2734. BABYLON.Vector3 = Vector3;
  2735. //Vector4 class created for EulerAngle class conversion to Quaternion
  2736. var Vector4 = /** @class */ (function () {
  2737. /**
  2738. * Creates a Vector4 object from the passed floats.
  2739. */
  2740. function Vector4(x, y, z, w) {
  2741. this.x = x;
  2742. this.y = y;
  2743. this.z = z;
  2744. this.w = w;
  2745. }
  2746. /**
  2747. * Returns the string with the Vector4 coordinates.
  2748. */
  2749. Vector4.prototype.toString = function () {
  2750. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2751. };
  2752. /**
  2753. * Returns the string "Vector4".
  2754. */
  2755. Vector4.prototype.getClassName = function () {
  2756. return "Vector4";
  2757. };
  2758. /**
  2759. * Returns the Vector4 hash code.
  2760. */
  2761. Vector4.prototype.getHashCode = function () {
  2762. var hash = this.x || 0;
  2763. hash = (hash * 397) ^ (this.y || 0);
  2764. hash = (hash * 397) ^ (this.z || 0);
  2765. hash = (hash * 397) ^ (this.w || 0);
  2766. return hash;
  2767. };
  2768. // Operators
  2769. /**
  2770. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2771. */
  2772. Vector4.prototype.asArray = function () {
  2773. var result = new Array();
  2774. this.toArray(result, 0);
  2775. return result;
  2776. };
  2777. /**
  2778. * Populates the passed array from the passed index with the Vector4 coordinates.
  2779. * Returns the Vector4.
  2780. */
  2781. Vector4.prototype.toArray = function (array, index) {
  2782. if (index === undefined) {
  2783. index = 0;
  2784. }
  2785. array[index] = this.x;
  2786. array[index + 1] = this.y;
  2787. array[index + 2] = this.z;
  2788. array[index + 3] = this.w;
  2789. return this;
  2790. };
  2791. /**
  2792. * Adds the passed vector to the current Vector4.
  2793. * Returns the updated Vector4.
  2794. */
  2795. Vector4.prototype.addInPlace = function (otherVector) {
  2796. this.x += otherVector.x;
  2797. this.y += otherVector.y;
  2798. this.z += otherVector.z;
  2799. this.w += otherVector.w;
  2800. return this;
  2801. };
  2802. /**
  2803. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2804. */
  2805. Vector4.prototype.add = function (otherVector) {
  2806. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2807. };
  2808. /**
  2809. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2810. * Returns the current Vector4.
  2811. */
  2812. Vector4.prototype.addToRef = function (otherVector, result) {
  2813. result.x = this.x + otherVector.x;
  2814. result.y = this.y + otherVector.y;
  2815. result.z = this.z + otherVector.z;
  2816. result.w = this.w + otherVector.w;
  2817. return this;
  2818. };
  2819. /**
  2820. * Subtract in place the passed vector from the current Vector4.
  2821. * Returns the updated Vector4.
  2822. */
  2823. Vector4.prototype.subtractInPlace = function (otherVector) {
  2824. this.x -= otherVector.x;
  2825. this.y -= otherVector.y;
  2826. this.z -= otherVector.z;
  2827. this.w -= otherVector.w;
  2828. return this;
  2829. };
  2830. /**
  2831. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2832. */
  2833. Vector4.prototype.subtract = function (otherVector) {
  2834. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2835. };
  2836. /**
  2837. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2838. * Returns the current Vector4.
  2839. */
  2840. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2841. result.x = this.x - otherVector.x;
  2842. result.y = this.y - otherVector.y;
  2843. result.z = this.z - otherVector.z;
  2844. result.w = this.w - otherVector.w;
  2845. return this;
  2846. };
  2847. /**
  2848. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2849. */
  2850. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2851. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2852. };
  2853. /**
  2854. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2855. * Returns the current Vector4.
  2856. */
  2857. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2858. result.x = this.x - x;
  2859. result.y = this.y - y;
  2860. result.z = this.z - z;
  2861. result.w = this.w - w;
  2862. return this;
  2863. };
  2864. /**
  2865. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2866. */
  2867. Vector4.prototype.negate = function () {
  2868. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2869. };
  2870. /**
  2871. * Multiplies the current Vector4 coordinates by scale (float).
  2872. * Returns the updated Vector4.
  2873. */
  2874. Vector4.prototype.scaleInPlace = function (scale) {
  2875. this.x *= scale;
  2876. this.y *= scale;
  2877. this.z *= scale;
  2878. this.w *= scale;
  2879. return this;
  2880. };
  2881. /**
  2882. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2883. */
  2884. Vector4.prototype.scale = function (scale) {
  2885. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2886. };
  2887. /**
  2888. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2889. * Returns the current Vector4.
  2890. */
  2891. Vector4.prototype.scaleToRef = function (scale, result) {
  2892. result.x = this.x * scale;
  2893. result.y = this.y * scale;
  2894. result.z = this.z * scale;
  2895. result.w = this.w * scale;
  2896. return this;
  2897. };
  2898. /**
  2899. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2900. */
  2901. Vector4.prototype.equals = function (otherVector) {
  2902. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2903. };
  2904. /**
  2905. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2906. */
  2907. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2908. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2909. return otherVector
  2910. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2911. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2912. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2913. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2914. };
  2915. /**
  2916. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2917. */
  2918. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2919. return this.x === x && this.y === y && this.z === z && this.w === w;
  2920. };
  2921. /**
  2922. * Multiplies in place the current Vector4 by the passed one.
  2923. * Returns the updated Vector4.
  2924. */
  2925. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2926. this.x *= otherVector.x;
  2927. this.y *= otherVector.y;
  2928. this.z *= otherVector.z;
  2929. this.w *= otherVector.w;
  2930. return this;
  2931. };
  2932. /**
  2933. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2934. */
  2935. Vector4.prototype.multiply = function (otherVector) {
  2936. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2937. };
  2938. /**
  2939. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2940. * Returns the current Vector4.
  2941. */
  2942. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2943. result.x = this.x * otherVector.x;
  2944. result.y = this.y * otherVector.y;
  2945. result.z = this.z * otherVector.z;
  2946. result.w = this.w * otherVector.w;
  2947. return this;
  2948. };
  2949. /**
  2950. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2951. */
  2952. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2953. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2954. };
  2955. /**
  2956. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2957. */
  2958. Vector4.prototype.divide = function (otherVector) {
  2959. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2960. };
  2961. /**
  2962. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2963. * Returns the current Vector4.
  2964. */
  2965. Vector4.prototype.divideToRef = function (otherVector, result) {
  2966. result.x = this.x / otherVector.x;
  2967. result.y = this.y / otherVector.y;
  2968. result.z = this.z / otherVector.z;
  2969. result.w = this.w / otherVector.w;
  2970. return this;
  2971. };
  2972. /**
  2973. * Divides the current Vector3 coordinates by the passed ones.
  2974. * Returns the updated Vector3.
  2975. */
  2976. Vector4.prototype.divideInPlace = function (otherVector) {
  2977. return this.divideToRef(otherVector, this);
  2978. };
  2979. /**
  2980. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2981. */
  2982. Vector4.prototype.MinimizeInPlace = function (other) {
  2983. if (other.x < this.x)
  2984. this.x = other.x;
  2985. if (other.y < this.y)
  2986. this.y = other.y;
  2987. if (other.z < this.z)
  2988. this.z = other.z;
  2989. if (other.w < this.w)
  2990. this.w = other.w;
  2991. return this;
  2992. };
  2993. /**
  2994. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2995. */
  2996. Vector4.prototype.MaximizeInPlace = function (other) {
  2997. if (other.x > this.x)
  2998. this.x = other.x;
  2999. if (other.y > this.y)
  3000. this.y = other.y;
  3001. if (other.z > this.z)
  3002. this.z = other.z;
  3003. if (other.w > this.w)
  3004. this.w = other.w;
  3005. return this;
  3006. };
  3007. // Properties
  3008. /**
  3009. * Returns the Vector4 length (float).
  3010. */
  3011. Vector4.prototype.length = function () {
  3012. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3013. };
  3014. /**
  3015. * Returns the Vector4 squared length (float).
  3016. */
  3017. Vector4.prototype.lengthSquared = function () {
  3018. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3019. };
  3020. // Methods
  3021. /**
  3022. * Normalizes in place the Vector4.
  3023. * Returns the updated Vector4.
  3024. */
  3025. Vector4.prototype.normalize = function () {
  3026. var len = this.length();
  3027. if (len === 0)
  3028. return this;
  3029. var num = 1.0 / len;
  3030. this.x *= num;
  3031. this.y *= num;
  3032. this.z *= num;
  3033. this.w *= num;
  3034. return this;
  3035. };
  3036. /**
  3037. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3038. */
  3039. Vector4.prototype.toVector3 = function () {
  3040. return new Vector3(this.x, this.y, this.z);
  3041. };
  3042. /**
  3043. * Returns a new Vector4 copied from the current one.
  3044. */
  3045. Vector4.prototype.clone = function () {
  3046. return new Vector4(this.x, this.y, this.z, this.w);
  3047. };
  3048. /**
  3049. * Updates the current Vector4 with the passed one coordinates.
  3050. * Returns the updated Vector4.
  3051. */
  3052. Vector4.prototype.copyFrom = function (source) {
  3053. this.x = source.x;
  3054. this.y = source.y;
  3055. this.z = source.z;
  3056. this.w = source.w;
  3057. return this;
  3058. };
  3059. /**
  3060. * Updates the current Vector4 coordinates with the passed floats.
  3061. * Returns the updated Vector4.
  3062. */
  3063. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3064. this.x = x;
  3065. this.y = y;
  3066. this.z = z;
  3067. this.w = w;
  3068. return this;
  3069. };
  3070. /**
  3071. * Updates the current Vector4 coordinates with the passed floats.
  3072. * Returns the updated Vector4.
  3073. */
  3074. Vector4.prototype.set = function (x, y, z, w) {
  3075. return this.copyFromFloats(x, y, z, w);
  3076. };
  3077. // Statics
  3078. /**
  3079. * Returns a new Vector4 set from the starting index of the passed array.
  3080. */
  3081. Vector4.FromArray = function (array, offset) {
  3082. if (!offset) {
  3083. offset = 0;
  3084. }
  3085. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3086. };
  3087. /**
  3088. * Updates the passed vector "result" from the starting index of the passed array.
  3089. */
  3090. Vector4.FromArrayToRef = function (array, offset, result) {
  3091. result.x = array[offset];
  3092. result.y = array[offset + 1];
  3093. result.z = array[offset + 2];
  3094. result.w = array[offset + 3];
  3095. };
  3096. /**
  3097. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3098. */
  3099. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3100. Vector4.FromArrayToRef(array, offset, result);
  3101. };
  3102. /**
  3103. * Updates the passed vector "result" coordinates from the passed floats.
  3104. */
  3105. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3106. result.x = x;
  3107. result.y = y;
  3108. result.z = z;
  3109. result.w = w;
  3110. };
  3111. /**
  3112. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3113. */
  3114. Vector4.Zero = function () {
  3115. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3116. };
  3117. /**
  3118. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3119. */
  3120. Vector4.One = function () {
  3121. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3122. };
  3123. /**
  3124. * Returns a new normalized Vector4 from the passed one.
  3125. */
  3126. Vector4.Normalize = function (vector) {
  3127. var result = Vector4.Zero();
  3128. Vector4.NormalizeToRef(vector, result);
  3129. return result;
  3130. };
  3131. /**
  3132. * Updates the passed vector "result" from the normalization of the passed one.
  3133. */
  3134. Vector4.NormalizeToRef = function (vector, result) {
  3135. result.copyFrom(vector);
  3136. result.normalize();
  3137. };
  3138. Vector4.Minimize = function (left, right) {
  3139. var min = left.clone();
  3140. min.MinimizeInPlace(right);
  3141. return min;
  3142. };
  3143. Vector4.Maximize = function (left, right) {
  3144. var max = left.clone();
  3145. max.MaximizeInPlace(right);
  3146. return max;
  3147. };
  3148. /**
  3149. * Returns the distance (float) between the vectors "value1" and "value2".
  3150. */
  3151. Vector4.Distance = function (value1, value2) {
  3152. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3153. };
  3154. /**
  3155. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3156. */
  3157. Vector4.DistanceSquared = function (value1, value2) {
  3158. var x = value1.x - value2.x;
  3159. var y = value1.y - value2.y;
  3160. var z = value1.z - value2.z;
  3161. var w = value1.w - value2.w;
  3162. return (x * x) + (y * y) + (z * z) + (w * w);
  3163. };
  3164. /**
  3165. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3166. */
  3167. Vector4.Center = function (value1, value2) {
  3168. var center = value1.add(value2);
  3169. center.scaleInPlace(0.5);
  3170. return center;
  3171. };
  3172. /**
  3173. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3174. * This methods computes transformed normalized direction vectors only.
  3175. */
  3176. Vector4.TransformNormal = function (vector, transformation) {
  3177. var result = Vector4.Zero();
  3178. Vector4.TransformNormalToRef(vector, transformation, result);
  3179. return result;
  3180. };
  3181. /**
  3182. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3183. * This methods computes transformed normalized direction vectors only.
  3184. */
  3185. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3186. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3187. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3188. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3189. result.x = x;
  3190. result.y = y;
  3191. result.z = z;
  3192. result.w = vector.w;
  3193. };
  3194. /**
  3195. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3196. * This methods computes transformed normalized direction vectors only.
  3197. */
  3198. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3199. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3200. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3201. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3202. result.w = w;
  3203. };
  3204. return Vector4;
  3205. }());
  3206. BABYLON.Vector4 = Vector4;
  3207. var Size = /** @class */ (function () {
  3208. /**
  3209. * Creates a Size object from the passed width and height (floats).
  3210. */
  3211. function Size(width, height) {
  3212. this.width = width;
  3213. this.height = height;
  3214. }
  3215. // Returns a string with the Size width and height.
  3216. Size.prototype.toString = function () {
  3217. return "{W: " + this.width + ", H: " + this.height + "}";
  3218. };
  3219. /**
  3220. * Returns the string "Size"
  3221. */
  3222. Size.prototype.getClassName = function () {
  3223. return "Size";
  3224. };
  3225. /**
  3226. * Returns the Size hash code.
  3227. */
  3228. Size.prototype.getHashCode = function () {
  3229. var hash = this.width || 0;
  3230. hash = (hash * 397) ^ (this.height || 0);
  3231. return hash;
  3232. };
  3233. /**
  3234. * Updates the current size from the passed one.
  3235. * Returns the updated Size.
  3236. */
  3237. Size.prototype.copyFrom = function (src) {
  3238. this.width = src.width;
  3239. this.height = src.height;
  3240. };
  3241. /**
  3242. * Updates in place the current Size from the passed floats.
  3243. * Returns the updated Size.
  3244. */
  3245. Size.prototype.copyFromFloats = function (width, height) {
  3246. this.width = width;
  3247. this.height = height;
  3248. return this;
  3249. };
  3250. /**
  3251. * Updates in place the current Size from the passed floats.
  3252. * Returns the updated Size.
  3253. */
  3254. Size.prototype.set = function (width, height) {
  3255. return this.copyFromFloats(width, height);
  3256. };
  3257. /**
  3258. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3259. */
  3260. Size.prototype.multiplyByFloats = function (w, h) {
  3261. return new Size(this.width * w, this.height * h);
  3262. };
  3263. /**
  3264. * Returns a new Size copied from the passed one.
  3265. */
  3266. Size.prototype.clone = function () {
  3267. return new Size(this.width, this.height);
  3268. };
  3269. /**
  3270. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3271. */
  3272. Size.prototype.equals = function (other) {
  3273. if (!other) {
  3274. return false;
  3275. }
  3276. return (this.width === other.width) && (this.height === other.height);
  3277. };
  3278. Object.defineProperty(Size.prototype, "surface", {
  3279. /**
  3280. * Returns the surface of the Size : width * height (float).
  3281. */
  3282. get: function () {
  3283. return this.width * this.height;
  3284. },
  3285. enumerable: true,
  3286. configurable: true
  3287. });
  3288. /**
  3289. * Returns a new Size set to (0.0, 0.0)
  3290. */
  3291. Size.Zero = function () {
  3292. return new Size(0.0, 0.0);
  3293. };
  3294. /**
  3295. * Returns a new Size set as the addition result of the current Size and the passed one.
  3296. */
  3297. Size.prototype.add = function (otherSize) {
  3298. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3299. return r;
  3300. };
  3301. /**
  3302. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3303. */
  3304. Size.prototype.subtract = function (otherSize) {
  3305. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3306. return r;
  3307. };
  3308. /**
  3309. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3310. */
  3311. Size.Lerp = function (start, end, amount) {
  3312. var w = start.width + ((end.width - start.width) * amount);
  3313. var h = start.height + ((end.height - start.height) * amount);
  3314. return new Size(w, h);
  3315. };
  3316. return Size;
  3317. }());
  3318. BABYLON.Size = Size;
  3319. var Quaternion = /** @class */ (function () {
  3320. /**
  3321. * Creates a new Quaternion from the passed floats.
  3322. */
  3323. function Quaternion(x, y, z, w) {
  3324. if (x === void 0) { x = 0.0; }
  3325. if (y === void 0) { y = 0.0; }
  3326. if (z === void 0) { z = 0.0; }
  3327. if (w === void 0) { w = 1.0; }
  3328. this.x = x;
  3329. this.y = y;
  3330. this.z = z;
  3331. this.w = w;
  3332. }
  3333. /**
  3334. * Returns a string with the Quaternion coordinates.
  3335. */
  3336. Quaternion.prototype.toString = function () {
  3337. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3338. };
  3339. /**
  3340. * Returns the string "Quaternion".
  3341. */
  3342. Quaternion.prototype.getClassName = function () {
  3343. return "Quaternion";
  3344. };
  3345. /**
  3346. * Returns the Quaternion hash code.
  3347. */
  3348. Quaternion.prototype.getHashCode = function () {
  3349. var hash = this.x || 0;
  3350. hash = (hash * 397) ^ (this.y || 0);
  3351. hash = (hash * 397) ^ (this.z || 0);
  3352. hash = (hash * 397) ^ (this.w || 0);
  3353. return hash;
  3354. };
  3355. /**
  3356. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3357. */
  3358. Quaternion.prototype.asArray = function () {
  3359. return [this.x, this.y, this.z, this.w];
  3360. };
  3361. /**
  3362. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3363. */
  3364. Quaternion.prototype.equals = function (otherQuaternion) {
  3365. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3366. };
  3367. /**
  3368. * Returns a new Quaternion copied from the current one.
  3369. */
  3370. Quaternion.prototype.clone = function () {
  3371. return new Quaternion(this.x, this.y, this.z, this.w);
  3372. };
  3373. /**
  3374. * Updates the current Quaternion from the passed one coordinates.
  3375. * Returns the updated Quaterion.
  3376. */
  3377. Quaternion.prototype.copyFrom = function (other) {
  3378. this.x = other.x;
  3379. this.y = other.y;
  3380. this.z = other.z;
  3381. this.w = other.w;
  3382. return this;
  3383. };
  3384. /**
  3385. * Updates the current Quaternion from the passed float coordinates.
  3386. * Returns the updated Quaterion.
  3387. */
  3388. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3389. this.x = x;
  3390. this.y = y;
  3391. this.z = z;
  3392. this.w = w;
  3393. return this;
  3394. };
  3395. /**
  3396. * Updates the current Quaternion from the passed float coordinates.
  3397. * Returns the updated Quaterion.
  3398. */
  3399. Quaternion.prototype.set = function (x, y, z, w) {
  3400. return this.copyFromFloats(x, y, z, w);
  3401. };
  3402. /**
  3403. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3404. */
  3405. Quaternion.prototype.add = function (other) {
  3406. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3407. };
  3408. /**
  3409. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3410. */
  3411. Quaternion.prototype.subtract = function (other) {
  3412. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3413. };
  3414. /**
  3415. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3416. */
  3417. Quaternion.prototype.scale = function (value) {
  3418. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3419. };
  3420. /**
  3421. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3422. */
  3423. Quaternion.prototype.multiply = function (q1) {
  3424. var result = new Quaternion(0, 0, 0, 1.0);
  3425. this.multiplyToRef(q1, result);
  3426. return result;
  3427. };
  3428. /**
  3429. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3430. * Returns the current Quaternion.
  3431. */
  3432. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3433. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3434. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3435. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3436. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3437. result.copyFromFloats(x, y, z, w);
  3438. return this;
  3439. };
  3440. /**
  3441. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3442. * Returns the updated Quaternion.
  3443. */
  3444. Quaternion.prototype.multiplyInPlace = function (q1) {
  3445. this.multiplyToRef(q1, this);
  3446. return this;
  3447. };
  3448. /**
  3449. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3450. * Returns the current Quaternion.
  3451. */
  3452. Quaternion.prototype.conjugateToRef = function (ref) {
  3453. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3454. return this;
  3455. };
  3456. /**
  3457. * Conjugates in place the current Quaternion.
  3458. * Returns the updated Quaternion.
  3459. */
  3460. Quaternion.prototype.conjugateInPlace = function () {
  3461. this.x *= -1;
  3462. this.y *= -1;
  3463. this.z *= -1;
  3464. return this;
  3465. };
  3466. /**
  3467. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3468. */
  3469. Quaternion.prototype.conjugate = function () {
  3470. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3471. return result;
  3472. };
  3473. /**
  3474. * Returns the Quaternion length (float).
  3475. */
  3476. Quaternion.prototype.length = function () {
  3477. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3478. };
  3479. /**
  3480. * Normalize in place the current Quaternion.
  3481. * Returns the updated Quaternion.
  3482. */
  3483. Quaternion.prototype.normalize = function () {
  3484. var length = 1.0 / this.length();
  3485. this.x *= length;
  3486. this.y *= length;
  3487. this.z *= length;
  3488. this.w *= length;
  3489. return this;
  3490. };
  3491. /**
  3492. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3493. */
  3494. Quaternion.prototype.toEulerAngles = function (order) {
  3495. if (order === void 0) { order = "YZX"; }
  3496. var result = Vector3.Zero();
  3497. this.toEulerAnglesToRef(result, order);
  3498. return result;
  3499. };
  3500. /**
  3501. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3502. * Returns the current Quaternion.
  3503. */
  3504. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3505. if (order === void 0) { order = "YZX"; }
  3506. var qz = this.z;
  3507. var qx = this.x;
  3508. var qy = this.y;
  3509. var qw = this.w;
  3510. var sqw = qw * qw;
  3511. var sqz = qz * qz;
  3512. var sqx = qx * qx;
  3513. var sqy = qy * qy;
  3514. var zAxisY = qy * qz - qx * qw;
  3515. var limit = .4999999;
  3516. if (zAxisY < -limit) {
  3517. result.y = 2 * Math.atan2(qy, qw);
  3518. result.x = Math.PI / 2;
  3519. result.z = 0;
  3520. }
  3521. else if (zAxisY > limit) {
  3522. result.y = 2 * Math.atan2(qy, qw);
  3523. result.x = -Math.PI / 2;
  3524. result.z = 0;
  3525. }
  3526. else {
  3527. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3528. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3529. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3530. }
  3531. return this;
  3532. };
  3533. /**
  3534. * Updates the passed rotation matrix with the current Quaternion values.
  3535. * Returns the current Quaternion.
  3536. */
  3537. Quaternion.prototype.toRotationMatrix = function (result) {
  3538. var xx = this.x * this.x;
  3539. var yy = this.y * this.y;
  3540. var zz = this.z * this.z;
  3541. var xy = this.x * this.y;
  3542. var zw = this.z * this.w;
  3543. var zx = this.z * this.x;
  3544. var yw = this.y * this.w;
  3545. var yz = this.y * this.z;
  3546. var xw = this.x * this.w;
  3547. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3548. result.m[1] = 2.0 * (xy + zw);
  3549. result.m[2] = 2.0 * (zx - yw);
  3550. result.m[3] = 0;
  3551. result.m[4] = 2.0 * (xy - zw);
  3552. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3553. result.m[6] = 2.0 * (yz + xw);
  3554. result.m[7] = 0;
  3555. result.m[8] = 2.0 * (zx + yw);
  3556. result.m[9] = 2.0 * (yz - xw);
  3557. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3558. result.m[11] = 0;
  3559. result.m[12] = 0;
  3560. result.m[13] = 0;
  3561. result.m[14] = 0;
  3562. result.m[15] = 1.0;
  3563. result._markAsUpdated();
  3564. return this;
  3565. };
  3566. /**
  3567. * Updates the current Quaternion from the passed rotation matrix values.
  3568. * Returns the updated Quaternion.
  3569. */
  3570. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3571. Quaternion.FromRotationMatrixToRef(matrix, this);
  3572. return this;
  3573. };
  3574. // Statics
  3575. /**
  3576. * Returns a new Quaternion set from the passed rotation matrix values.
  3577. */
  3578. Quaternion.FromRotationMatrix = function (matrix) {
  3579. var result = new Quaternion();
  3580. Quaternion.FromRotationMatrixToRef(matrix, result);
  3581. return result;
  3582. };
  3583. /**
  3584. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3585. */
  3586. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3587. var data = matrix.m;
  3588. var m11 = data[0], m12 = data[4], m13 = data[8];
  3589. var m21 = data[1], m22 = data[5], m23 = data[9];
  3590. var m31 = data[2], m32 = data[6], m33 = data[10];
  3591. var trace = m11 + m22 + m33;
  3592. var s;
  3593. if (trace > 0) {
  3594. s = 0.5 / Math.sqrt(trace + 1.0);
  3595. result.w = 0.25 / s;
  3596. result.x = (m32 - m23) * s;
  3597. result.y = (m13 - m31) * s;
  3598. result.z = (m21 - m12) * s;
  3599. }
  3600. else if (m11 > m22 && m11 > m33) {
  3601. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3602. result.w = (m32 - m23) / s;
  3603. result.x = 0.25 * s;
  3604. result.y = (m12 + m21) / s;
  3605. result.z = (m13 + m31) / s;
  3606. }
  3607. else if (m22 > m33) {
  3608. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3609. result.w = (m13 - m31) / s;
  3610. result.x = (m12 + m21) / s;
  3611. result.y = 0.25 * s;
  3612. result.z = (m23 + m32) / s;
  3613. }
  3614. else {
  3615. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3616. result.w = (m21 - m12) / s;
  3617. result.x = (m13 + m31) / s;
  3618. result.y = (m23 + m32) / s;
  3619. result.z = 0.25 * s;
  3620. }
  3621. };
  3622. /**
  3623. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3624. */
  3625. Quaternion.Zero = function () {
  3626. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3627. };
  3628. /**
  3629. * Returns a new Quaternion as the inverted current Quaternion.
  3630. */
  3631. Quaternion.Inverse = function (q) {
  3632. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3633. };
  3634. /**
  3635. * Returns the identity Quaternion.
  3636. */
  3637. Quaternion.Identity = function () {
  3638. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3639. };
  3640. Quaternion.IsIdentity = function (quaternion) {
  3641. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3642. };
  3643. /**
  3644. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3645. */
  3646. Quaternion.RotationAxis = function (axis, angle) {
  3647. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3648. };
  3649. /**
  3650. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3651. */
  3652. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3653. var sin = Math.sin(angle / 2);
  3654. axis.normalize();
  3655. result.w = Math.cos(angle / 2);
  3656. result.x = axis.x * sin;
  3657. result.y = axis.y * sin;
  3658. result.z = axis.z * sin;
  3659. return result;
  3660. };
  3661. /**
  3662. * Retuns a new Quaternion set from the starting index of the passed array.
  3663. */
  3664. Quaternion.FromArray = function (array, offset) {
  3665. if (!offset) {
  3666. offset = 0;
  3667. }
  3668. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3669. };
  3670. /**
  3671. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3672. */
  3673. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3674. var q = new Quaternion();
  3675. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3676. return q;
  3677. };
  3678. /**
  3679. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3680. */
  3681. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3682. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3683. var halfRoll = roll * 0.5;
  3684. var halfPitch = pitch * 0.5;
  3685. var halfYaw = yaw * 0.5;
  3686. var sinRoll = Math.sin(halfRoll);
  3687. var cosRoll = Math.cos(halfRoll);
  3688. var sinPitch = Math.sin(halfPitch);
  3689. var cosPitch = Math.cos(halfPitch);
  3690. var sinYaw = Math.sin(halfYaw);
  3691. var cosYaw = Math.cos(halfYaw);
  3692. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3693. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3694. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3695. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3696. };
  3697. /**
  3698. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3699. */
  3700. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3701. var result = new Quaternion();
  3702. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3703. return result;
  3704. };
  3705. /**
  3706. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3707. */
  3708. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3709. // Produces a quaternion from Euler angles in the z-x-z orientation
  3710. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3711. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3712. var halfBeta = beta * 0.5;
  3713. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3714. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3715. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3716. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3717. };
  3718. /**
  3719. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3720. * cf to Vector3.RotationFromAxis() documentation.
  3721. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3722. */
  3723. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3724. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3725. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3726. return quat;
  3727. };
  3728. /**
  3729. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3730. * cf to Vector3.RotationFromAxis() documentation.
  3731. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3732. */
  3733. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3734. var rotMat = MathTmp.Matrix[0];
  3735. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3736. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3737. };
  3738. Quaternion.Slerp = function (left, right, amount) {
  3739. var result = Quaternion.Identity();
  3740. Quaternion.SlerpToRef(left, right, amount, result);
  3741. return result;
  3742. };
  3743. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3744. var num2;
  3745. var num3;
  3746. var num = amount;
  3747. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3748. var flag = false;
  3749. if (num4 < 0) {
  3750. flag = true;
  3751. num4 = -num4;
  3752. }
  3753. if (num4 > 0.999999) {
  3754. num3 = 1 - num;
  3755. num2 = flag ? -num : num;
  3756. }
  3757. else {
  3758. var num5 = Math.acos(num4);
  3759. var num6 = (1.0 / Math.sin(num5));
  3760. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3761. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3762. }
  3763. result.x = (num3 * left.x) + (num2 * right.x);
  3764. result.y = (num3 * left.y) + (num2 * right.y);
  3765. result.z = (num3 * left.z) + (num2 * right.z);
  3766. result.w = (num3 * left.w) + (num2 * right.w);
  3767. };
  3768. /**
  3769. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3770. */
  3771. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3772. var squared = amount * amount;
  3773. var cubed = amount * squared;
  3774. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3775. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3776. var part3 = (cubed - (2.0 * squared)) + amount;
  3777. var part4 = cubed - squared;
  3778. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3779. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3780. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3781. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3782. return new Quaternion(x, y, z, w);
  3783. };
  3784. return Quaternion;
  3785. }());
  3786. BABYLON.Quaternion = Quaternion;
  3787. var Matrix = /** @class */ (function () {
  3788. function Matrix() {
  3789. this._isIdentity = false;
  3790. this._isIdentityDirty = true;
  3791. this.m = new Float32Array(16);
  3792. this._markAsUpdated();
  3793. }
  3794. Matrix.prototype._markAsUpdated = function () {
  3795. this.updateFlag = Matrix._updateFlagSeed++;
  3796. this._isIdentityDirty = true;
  3797. };
  3798. // Properties
  3799. /**
  3800. * Boolean : True is the matrix is the identity matrix
  3801. */
  3802. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3803. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3804. if (this._isIdentityDirty) {
  3805. this._isIdentityDirty = false;
  3806. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3807. this._isIdentity = false;
  3808. }
  3809. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3810. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3811. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3812. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3813. this._isIdentity = false;
  3814. }
  3815. else {
  3816. this._isIdentity = true;
  3817. }
  3818. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3819. this._isIdentity = false;
  3820. }
  3821. }
  3822. return this._isIdentity;
  3823. };
  3824. /**
  3825. * Returns the matrix determinant (float).
  3826. */
  3827. Matrix.prototype.determinant = function () {
  3828. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3829. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3830. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3831. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3832. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3833. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3834. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3835. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3836. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3837. };
  3838. // Methods
  3839. /**
  3840. * Returns the matrix underlying array.
  3841. */
  3842. Matrix.prototype.toArray = function () {
  3843. return this.m;
  3844. };
  3845. /**
  3846. * Returns the matrix underlying array.
  3847. */
  3848. Matrix.prototype.asArray = function () {
  3849. return this.toArray();
  3850. };
  3851. /**
  3852. * Inverts in place the Matrix.
  3853. * Returns the Matrix inverted.
  3854. */
  3855. Matrix.prototype.invert = function () {
  3856. this.invertToRef(this);
  3857. return this;
  3858. };
  3859. /**
  3860. * Sets all the matrix elements to zero.
  3861. * Returns the Matrix.
  3862. */
  3863. Matrix.prototype.reset = function () {
  3864. for (var index = 0; index < 16; index++) {
  3865. this.m[index] = 0.0;
  3866. }
  3867. this._markAsUpdated();
  3868. return this;
  3869. };
  3870. /**
  3871. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3872. */
  3873. Matrix.prototype.add = function (other) {
  3874. var result = new Matrix();
  3875. this.addToRef(other, result);
  3876. return result;
  3877. };
  3878. /**
  3879. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3880. * Returns the Matrix.
  3881. */
  3882. Matrix.prototype.addToRef = function (other, result) {
  3883. for (var index = 0; index < 16; index++) {
  3884. result.m[index] = this.m[index] + other.m[index];
  3885. }
  3886. result._markAsUpdated();
  3887. return this;
  3888. };
  3889. /**
  3890. * Adds in place the passed matrix to the current Matrix.
  3891. * Returns the updated Matrix.
  3892. */
  3893. Matrix.prototype.addToSelf = function (other) {
  3894. for (var index = 0; index < 16; index++) {
  3895. this.m[index] += other.m[index];
  3896. }
  3897. this._markAsUpdated();
  3898. return this;
  3899. };
  3900. /**
  3901. * Sets the passed matrix with the current inverted Matrix.
  3902. * Returns the unmodified current Matrix.
  3903. */
  3904. Matrix.prototype.invertToRef = function (other) {
  3905. var l1 = this.m[0];
  3906. var l2 = this.m[1];
  3907. var l3 = this.m[2];
  3908. var l4 = this.m[3];
  3909. var l5 = this.m[4];
  3910. var l6 = this.m[5];
  3911. var l7 = this.m[6];
  3912. var l8 = this.m[7];
  3913. var l9 = this.m[8];
  3914. var l10 = this.m[9];
  3915. var l11 = this.m[10];
  3916. var l12 = this.m[11];
  3917. var l13 = this.m[12];
  3918. var l14 = this.m[13];
  3919. var l15 = this.m[14];
  3920. var l16 = this.m[15];
  3921. var l17 = (l11 * l16) - (l12 * l15);
  3922. var l18 = (l10 * l16) - (l12 * l14);
  3923. var l19 = (l10 * l15) - (l11 * l14);
  3924. var l20 = (l9 * l16) - (l12 * l13);
  3925. var l21 = (l9 * l15) - (l11 * l13);
  3926. var l22 = (l9 * l14) - (l10 * l13);
  3927. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3928. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3929. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3930. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3931. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3932. var l28 = (l7 * l16) - (l8 * l15);
  3933. var l29 = (l6 * l16) - (l8 * l14);
  3934. var l30 = (l6 * l15) - (l7 * l14);
  3935. var l31 = (l5 * l16) - (l8 * l13);
  3936. var l32 = (l5 * l15) - (l7 * l13);
  3937. var l33 = (l5 * l14) - (l6 * l13);
  3938. var l34 = (l7 * l12) - (l8 * l11);
  3939. var l35 = (l6 * l12) - (l8 * l10);
  3940. var l36 = (l6 * l11) - (l7 * l10);
  3941. var l37 = (l5 * l12) - (l8 * l9);
  3942. var l38 = (l5 * l11) - (l7 * l9);
  3943. var l39 = (l5 * l10) - (l6 * l9);
  3944. other.m[0] = l23 * l27;
  3945. other.m[4] = l24 * l27;
  3946. other.m[8] = l25 * l27;
  3947. other.m[12] = l26 * l27;
  3948. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3949. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3950. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3951. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3952. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3953. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3954. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3955. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3956. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3957. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3958. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3959. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3960. other._markAsUpdated();
  3961. return this;
  3962. };
  3963. /**
  3964. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3965. * Returns the updated Matrix.
  3966. */
  3967. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3968. this.m[12] = x;
  3969. this.m[13] = y;
  3970. this.m[14] = z;
  3971. this._markAsUpdated();
  3972. return this;
  3973. };
  3974. /**
  3975. * Inserts the translation vector in the current Matrix.
  3976. * Returns the updated Matrix.
  3977. */
  3978. Matrix.prototype.setTranslation = function (vector3) {
  3979. this.m[12] = vector3.x;
  3980. this.m[13] = vector3.y;
  3981. this.m[14] = vector3.z;
  3982. this._markAsUpdated();
  3983. return this;
  3984. };
  3985. /**
  3986. * Returns a new Vector3 as the extracted translation from the Matrix.
  3987. */
  3988. Matrix.prototype.getTranslation = function () {
  3989. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3990. };
  3991. /**
  3992. * Fill a Vector3 with the extracted translation from the Matrix.
  3993. */
  3994. Matrix.prototype.getTranslationToRef = function (result) {
  3995. result.x = this.m[12];
  3996. result.y = this.m[13];
  3997. result.z = this.m[14];
  3998. return this;
  3999. };
  4000. /**
  4001. * Remove rotation and scaling part from the Matrix.
  4002. * Returns the updated Matrix.
  4003. */
  4004. Matrix.prototype.removeRotationAndScaling = function () {
  4005. this.setRowFromFloats(0, 1, 0, 0, 0);
  4006. this.setRowFromFloats(1, 0, 1, 0, 0);
  4007. this.setRowFromFloats(2, 0, 0, 1, 0);
  4008. return this;
  4009. };
  4010. /**
  4011. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4012. */
  4013. Matrix.prototype.multiply = function (other) {
  4014. var result = new Matrix();
  4015. this.multiplyToRef(other, result);
  4016. return result;
  4017. };
  4018. /**
  4019. * Updates the current Matrix from the passed one values.
  4020. * Returns the updated Matrix.
  4021. */
  4022. Matrix.prototype.copyFrom = function (other) {
  4023. for (var index = 0; index < 16; index++) {
  4024. this.m[index] = other.m[index];
  4025. }
  4026. this._markAsUpdated();
  4027. return this;
  4028. };
  4029. /**
  4030. * Populates the passed array from the starting index with the Matrix values.
  4031. * Returns the Matrix.
  4032. */
  4033. Matrix.prototype.copyToArray = function (array, offset) {
  4034. if (offset === void 0) { offset = 0; }
  4035. for (var index = 0; index < 16; index++) {
  4036. array[offset + index] = this.m[index];
  4037. }
  4038. return this;
  4039. };
  4040. /**
  4041. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4042. */
  4043. Matrix.prototype.multiplyToRef = function (other, result) {
  4044. this.multiplyToArray(other, result.m, 0);
  4045. result._markAsUpdated();
  4046. return this;
  4047. };
  4048. /**
  4049. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4050. */
  4051. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4052. var tm0 = this.m[0];
  4053. var tm1 = this.m[1];
  4054. var tm2 = this.m[2];
  4055. var tm3 = this.m[3];
  4056. var tm4 = this.m[4];
  4057. var tm5 = this.m[5];
  4058. var tm6 = this.m[6];
  4059. var tm7 = this.m[7];
  4060. var tm8 = this.m[8];
  4061. var tm9 = this.m[9];
  4062. var tm10 = this.m[10];
  4063. var tm11 = this.m[11];
  4064. var tm12 = this.m[12];
  4065. var tm13 = this.m[13];
  4066. var tm14 = this.m[14];
  4067. var tm15 = this.m[15];
  4068. var om0 = other.m[0];
  4069. var om1 = other.m[1];
  4070. var om2 = other.m[2];
  4071. var om3 = other.m[3];
  4072. var om4 = other.m[4];
  4073. var om5 = other.m[5];
  4074. var om6 = other.m[6];
  4075. var om7 = other.m[7];
  4076. var om8 = other.m[8];
  4077. var om9 = other.m[9];
  4078. var om10 = other.m[10];
  4079. var om11 = other.m[11];
  4080. var om12 = other.m[12];
  4081. var om13 = other.m[13];
  4082. var om14 = other.m[14];
  4083. var om15 = other.m[15];
  4084. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4085. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4086. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4087. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4088. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4089. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4090. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4091. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4092. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4093. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4094. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4095. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4096. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4097. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4098. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4099. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4100. return this;
  4101. };
  4102. /**
  4103. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4104. */
  4105. Matrix.prototype.equals = function (value) {
  4106. return value &&
  4107. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4108. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4109. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4110. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4111. };
  4112. /**
  4113. * Returns a new Matrix from the current Matrix.
  4114. */
  4115. Matrix.prototype.clone = function () {
  4116. 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]);
  4117. };
  4118. /**
  4119. * Returns the string "Matrix"
  4120. */
  4121. Matrix.prototype.getClassName = function () {
  4122. return "Matrix";
  4123. };
  4124. /**
  4125. * Returns the Matrix hash code.
  4126. */
  4127. Matrix.prototype.getHashCode = function () {
  4128. var hash = this.m[0] || 0;
  4129. for (var i = 1; i < 16; i++) {
  4130. hash = (hash * 397) ^ (this.m[i] || 0);
  4131. }
  4132. return hash;
  4133. };
  4134. /**
  4135. * Decomposes the current Matrix into :
  4136. * - a scale vector3 passed as a reference to update,
  4137. * - a rotation quaternion passed as a reference to update,
  4138. * - a translation vector3 passed as a reference to update.
  4139. * Returns the boolean `true`.
  4140. */
  4141. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4142. translation.x = this.m[12];
  4143. translation.y = this.m[13];
  4144. translation.z = this.m[14];
  4145. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4146. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4147. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4148. if (this.determinant() <= 0) {
  4149. scale.y *= -1;
  4150. }
  4151. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4152. rotation.x = 0;
  4153. rotation.y = 0;
  4154. rotation.z = 0;
  4155. rotation.w = 1;
  4156. return false;
  4157. }
  4158. 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]);
  4159. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4160. return true;
  4161. };
  4162. /**
  4163. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4164. */
  4165. Matrix.prototype.getRotationMatrix = function () {
  4166. var result = Matrix.Identity();
  4167. this.getRotationMatrixToRef(result);
  4168. return result;
  4169. };
  4170. /**
  4171. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4172. * Returns the current Matrix.
  4173. */
  4174. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4175. var m = this.m;
  4176. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4177. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4178. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4179. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4180. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4181. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4182. 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);
  4183. return this;
  4184. };
  4185. // Statics
  4186. /**
  4187. * Returns a new Matrix set from the starting index of the passed array.
  4188. */
  4189. Matrix.FromArray = function (array, offset) {
  4190. var result = new Matrix();
  4191. if (!offset) {
  4192. offset = 0;
  4193. }
  4194. Matrix.FromArrayToRef(array, offset, result);
  4195. return result;
  4196. };
  4197. /**
  4198. * Sets the passed "result" matrix from the starting index of the passed array.
  4199. */
  4200. Matrix.FromArrayToRef = function (array, offset, result) {
  4201. for (var index = 0; index < 16; index++) {
  4202. result.m[index] = array[index + offset];
  4203. }
  4204. result._markAsUpdated();
  4205. };
  4206. /**
  4207. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4208. */
  4209. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4210. for (var index = 0; index < 16; index++) {
  4211. result.m[index] = array[index + offset] * scale;
  4212. }
  4213. result._markAsUpdated();
  4214. };
  4215. /**
  4216. * Sets the passed matrix "result" with the 16 passed floats.
  4217. */
  4218. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4219. result.m[0] = initialM11;
  4220. result.m[1] = initialM12;
  4221. result.m[2] = initialM13;
  4222. result.m[3] = initialM14;
  4223. result.m[4] = initialM21;
  4224. result.m[5] = initialM22;
  4225. result.m[6] = initialM23;
  4226. result.m[7] = initialM24;
  4227. result.m[8] = initialM31;
  4228. result.m[9] = initialM32;
  4229. result.m[10] = initialM33;
  4230. result.m[11] = initialM34;
  4231. result.m[12] = initialM41;
  4232. result.m[13] = initialM42;
  4233. result.m[14] = initialM43;
  4234. result.m[15] = initialM44;
  4235. result._markAsUpdated();
  4236. };
  4237. /**
  4238. * Returns the index-th row of the current matrix as a new Vector4.
  4239. */
  4240. Matrix.prototype.getRow = function (index) {
  4241. if (index < 0 || index > 3) {
  4242. return null;
  4243. }
  4244. var i = index * 4;
  4245. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4246. };
  4247. /**
  4248. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4249. * Returns the updated Matrix.
  4250. */
  4251. Matrix.prototype.setRow = function (index, row) {
  4252. if (index < 0 || index > 3) {
  4253. return this;
  4254. }
  4255. var i = index * 4;
  4256. this.m[i + 0] = row.x;
  4257. this.m[i + 1] = row.y;
  4258. this.m[i + 2] = row.z;
  4259. this.m[i + 3] = row.w;
  4260. this._markAsUpdated();
  4261. return this;
  4262. };
  4263. /**
  4264. * Compute the transpose of the matrix.
  4265. * Returns a new Matrix.
  4266. */
  4267. Matrix.prototype.transpose = function () {
  4268. return Matrix.Transpose(this);
  4269. };
  4270. /**
  4271. * Compute the transpose of the matrix.
  4272. * Returns the current matrix.
  4273. */
  4274. Matrix.prototype.transposeToRef = function (result) {
  4275. Matrix.TransposeToRef(this, result);
  4276. return this;
  4277. };
  4278. /**
  4279. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4280. * Returns the updated Matrix.
  4281. */
  4282. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4283. if (index < 0 || index > 3) {
  4284. return this;
  4285. }
  4286. var i = index * 4;
  4287. this.m[i + 0] = x;
  4288. this.m[i + 1] = y;
  4289. this.m[i + 2] = z;
  4290. this.m[i + 3] = w;
  4291. this._markAsUpdated();
  4292. return this;
  4293. };
  4294. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4295. /**
  4296. * Static identity matrix to be used as readonly matrix
  4297. * Must not be updated.
  4298. */
  4299. get: function () {
  4300. return Matrix._identityReadOnly;
  4301. },
  4302. enumerable: true,
  4303. configurable: true
  4304. });
  4305. /**
  4306. * Returns a new Matrix set from the 16 passed floats.
  4307. */
  4308. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4309. var result = new Matrix();
  4310. result.m[0] = initialM11;
  4311. result.m[1] = initialM12;
  4312. result.m[2] = initialM13;
  4313. result.m[3] = initialM14;
  4314. result.m[4] = initialM21;
  4315. result.m[5] = initialM22;
  4316. result.m[6] = initialM23;
  4317. result.m[7] = initialM24;
  4318. result.m[8] = initialM31;
  4319. result.m[9] = initialM32;
  4320. result.m[10] = initialM33;
  4321. result.m[11] = initialM34;
  4322. result.m[12] = initialM41;
  4323. result.m[13] = initialM42;
  4324. result.m[14] = initialM43;
  4325. result.m[15] = initialM44;
  4326. return result;
  4327. };
  4328. /**
  4329. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4330. */
  4331. Matrix.Compose = function (scale, rotation, translation) {
  4332. var result = Matrix.Identity();
  4333. Matrix.ComposeToRef(scale, rotation, translation, result);
  4334. return result;
  4335. };
  4336. /**
  4337. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4338. */
  4339. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4340. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4341. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4342. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4343. result.setTranslation(translation);
  4344. };
  4345. /**
  4346. * Returns a new indentity Matrix.
  4347. */
  4348. Matrix.Identity = function () {
  4349. 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);
  4350. };
  4351. /**
  4352. * Sets the passed "result" as an identity matrix.
  4353. */
  4354. Matrix.IdentityToRef = function (result) {
  4355. 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);
  4356. };
  4357. /**
  4358. * Returns a new zero Matrix.
  4359. */
  4360. Matrix.Zero = function () {
  4361. 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);
  4362. };
  4363. /**
  4364. * Returns a new rotation matrix for "angle" radians around the X axis.
  4365. */
  4366. Matrix.RotationX = function (angle) {
  4367. var result = new Matrix();
  4368. Matrix.RotationXToRef(angle, result);
  4369. return result;
  4370. };
  4371. /**
  4372. * Returns a new Matrix as the passed inverted one.
  4373. */
  4374. Matrix.Invert = function (source) {
  4375. var result = new Matrix();
  4376. source.invertToRef(result);
  4377. return result;
  4378. };
  4379. /**
  4380. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4381. */
  4382. Matrix.RotationXToRef = function (angle, result) {
  4383. var s = Math.sin(angle);
  4384. var c = Math.cos(angle);
  4385. result.m[0] = 1.0;
  4386. result.m[15] = 1.0;
  4387. result.m[5] = c;
  4388. result.m[10] = c;
  4389. result.m[9] = -s;
  4390. result.m[6] = s;
  4391. result.m[1] = 0.0;
  4392. result.m[2] = 0.0;
  4393. result.m[3] = 0.0;
  4394. result.m[4] = 0.0;
  4395. result.m[7] = 0.0;
  4396. result.m[8] = 0.0;
  4397. result.m[11] = 0.0;
  4398. result.m[12] = 0.0;
  4399. result.m[13] = 0.0;
  4400. result.m[14] = 0.0;
  4401. result._markAsUpdated();
  4402. };
  4403. /**
  4404. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4405. */
  4406. Matrix.RotationY = function (angle) {
  4407. var result = new Matrix();
  4408. Matrix.RotationYToRef(angle, result);
  4409. return result;
  4410. };
  4411. /**
  4412. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4413. */
  4414. Matrix.RotationYToRef = function (angle, result) {
  4415. var s = Math.sin(angle);
  4416. var c = Math.cos(angle);
  4417. result.m[5] = 1.0;
  4418. result.m[15] = 1.0;
  4419. result.m[0] = c;
  4420. result.m[2] = -s;
  4421. result.m[8] = s;
  4422. result.m[10] = c;
  4423. result.m[1] = 0.0;
  4424. result.m[3] = 0.0;
  4425. result.m[4] = 0.0;
  4426. result.m[6] = 0.0;
  4427. result.m[7] = 0.0;
  4428. result.m[9] = 0.0;
  4429. result.m[11] = 0.0;
  4430. result.m[12] = 0.0;
  4431. result.m[13] = 0.0;
  4432. result.m[14] = 0.0;
  4433. result._markAsUpdated();
  4434. };
  4435. /**
  4436. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4437. */
  4438. Matrix.RotationZ = function (angle) {
  4439. var result = new Matrix();
  4440. Matrix.RotationZToRef(angle, result);
  4441. return result;
  4442. };
  4443. /**
  4444. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4445. */
  4446. Matrix.RotationZToRef = function (angle, result) {
  4447. var s = Math.sin(angle);
  4448. var c = Math.cos(angle);
  4449. result.m[10] = 1.0;
  4450. result.m[15] = 1.0;
  4451. result.m[0] = c;
  4452. result.m[1] = s;
  4453. result.m[4] = -s;
  4454. result.m[5] = c;
  4455. result.m[2] = 0.0;
  4456. result.m[3] = 0.0;
  4457. result.m[6] = 0.0;
  4458. result.m[7] = 0.0;
  4459. result.m[8] = 0.0;
  4460. result.m[9] = 0.0;
  4461. result.m[11] = 0.0;
  4462. result.m[12] = 0.0;
  4463. result.m[13] = 0.0;
  4464. result.m[14] = 0.0;
  4465. result._markAsUpdated();
  4466. };
  4467. /**
  4468. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4469. */
  4470. Matrix.RotationAxis = function (axis, angle) {
  4471. var result = Matrix.Zero();
  4472. Matrix.RotationAxisToRef(axis, angle, result);
  4473. return result;
  4474. };
  4475. /**
  4476. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4477. */
  4478. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4479. var s = Math.sin(-angle);
  4480. var c = Math.cos(-angle);
  4481. var c1 = 1 - c;
  4482. axis.normalize();
  4483. result.m[0] = (axis.x * axis.x) * c1 + c;
  4484. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4485. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4486. result.m[3] = 0.0;
  4487. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4488. result.m[5] = (axis.y * axis.y) * c1 + c;
  4489. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4490. result.m[7] = 0.0;
  4491. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4492. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4493. result.m[10] = (axis.z * axis.z) * c1 + c;
  4494. result.m[11] = 0.0;
  4495. result.m[15] = 1.0;
  4496. result._markAsUpdated();
  4497. };
  4498. /**
  4499. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4500. */
  4501. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4502. var result = new Matrix();
  4503. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4504. return result;
  4505. };
  4506. /**
  4507. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4508. */
  4509. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4510. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4511. this._tempQuaternion.toRotationMatrix(result);
  4512. };
  4513. /**
  4514. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4515. */
  4516. Matrix.Scaling = function (x, y, z) {
  4517. var result = Matrix.Zero();
  4518. Matrix.ScalingToRef(x, y, z, result);
  4519. return result;
  4520. };
  4521. /**
  4522. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4523. */
  4524. Matrix.ScalingToRef = function (x, y, z, result) {
  4525. result.m[0] = x;
  4526. result.m[1] = 0.0;
  4527. result.m[2] = 0.0;
  4528. result.m[3] = 0.0;
  4529. result.m[4] = 0.0;
  4530. result.m[5] = y;
  4531. result.m[6] = 0.0;
  4532. result.m[7] = 0.0;
  4533. result.m[8] = 0.0;
  4534. result.m[9] = 0.0;
  4535. result.m[10] = z;
  4536. result.m[11] = 0.0;
  4537. result.m[12] = 0.0;
  4538. result.m[13] = 0.0;
  4539. result.m[14] = 0.0;
  4540. result.m[15] = 1.0;
  4541. result._markAsUpdated();
  4542. };
  4543. /**
  4544. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4545. */
  4546. Matrix.Translation = function (x, y, z) {
  4547. var result = Matrix.Identity();
  4548. Matrix.TranslationToRef(x, y, z, result);
  4549. return result;
  4550. };
  4551. /**
  4552. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4553. */
  4554. Matrix.TranslationToRef = function (x, y, z, result) {
  4555. 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);
  4556. };
  4557. /**
  4558. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4559. */
  4560. Matrix.Lerp = function (startValue, endValue, gradient) {
  4561. var result = Matrix.Zero();
  4562. for (var index = 0; index < 16; index++) {
  4563. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4564. }
  4565. result._markAsUpdated();
  4566. return result;
  4567. };
  4568. /**
  4569. * Returns a new Matrix whose values are computed by :
  4570. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4571. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4572. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4573. */
  4574. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4575. var startScale = new Vector3(0, 0, 0);
  4576. var startRotation = new Quaternion();
  4577. var startTranslation = new Vector3(0, 0, 0);
  4578. startValue.decompose(startScale, startRotation, startTranslation);
  4579. var endScale = new Vector3(0, 0, 0);
  4580. var endRotation = new Quaternion();
  4581. var endTranslation = new Vector3(0, 0, 0);
  4582. endValue.decompose(endScale, endRotation, endTranslation);
  4583. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4584. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4585. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4586. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4587. };
  4588. /**
  4589. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4590. * This methods works for a Left-Handed system.
  4591. */
  4592. Matrix.LookAtLH = function (eye, target, up) {
  4593. var result = Matrix.Zero();
  4594. Matrix.LookAtLHToRef(eye, target, up, result);
  4595. return result;
  4596. };
  4597. /**
  4598. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4599. * This methods works for a Left-Handed system.
  4600. */
  4601. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4602. // Z axis
  4603. target.subtractToRef(eye, this._zAxis);
  4604. this._zAxis.normalize();
  4605. // X axis
  4606. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4607. if (this._xAxis.lengthSquared() === 0) {
  4608. this._xAxis.x = 1.0;
  4609. }
  4610. else {
  4611. this._xAxis.normalize();
  4612. }
  4613. // Y axis
  4614. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4615. this._yAxis.normalize();
  4616. // Eye angles
  4617. var ex = -Vector3.Dot(this._xAxis, eye);
  4618. var ey = -Vector3.Dot(this._yAxis, eye);
  4619. var ez = -Vector3.Dot(this._zAxis, eye);
  4620. 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);
  4621. };
  4622. /**
  4623. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4624. * This methods works for a Right-Handed system.
  4625. */
  4626. Matrix.LookAtRH = function (eye, target, up) {
  4627. var result = Matrix.Zero();
  4628. Matrix.LookAtRHToRef(eye, target, up, result);
  4629. return result;
  4630. };
  4631. /**
  4632. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  4633. * This methods works for a Left-Handed system.
  4634. */
  4635. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4636. // Z axis
  4637. eye.subtractToRef(target, this._zAxis);
  4638. this._zAxis.normalize();
  4639. // X axis
  4640. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4641. if (this._xAxis.lengthSquared() === 0) {
  4642. this._xAxis.x = 1.0;
  4643. }
  4644. else {
  4645. this._xAxis.normalize();
  4646. }
  4647. // Y axis
  4648. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4649. this._yAxis.normalize();
  4650. // Eye angles
  4651. var ex = -Vector3.Dot(this._xAxis, eye);
  4652. var ey = -Vector3.Dot(this._yAxis, eye);
  4653. var ez = -Vector3.Dot(this._zAxis, eye);
  4654. 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);
  4655. };
  4656. /**
  4657. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4658. */
  4659. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4660. var matrix = Matrix.Zero();
  4661. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4662. return matrix;
  4663. };
  4664. /**
  4665. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4666. */
  4667. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4668. var n = znear;
  4669. var f = zfar;
  4670. var a = 2.0 / width;
  4671. var b = 2.0 / height;
  4672. var c = 2.0 / (f - n);
  4673. var d = -(f + n) / (f - n);
  4674. 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);
  4675. };
  4676. /**
  4677. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4678. */
  4679. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4680. var matrix = Matrix.Zero();
  4681. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4682. return matrix;
  4683. };
  4684. /**
  4685. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4686. */
  4687. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4688. var n = znear;
  4689. var f = zfar;
  4690. var a = 2.0 / (right - left);
  4691. var b = 2.0 / (top - bottom);
  4692. var c = 2.0 / (f - n);
  4693. var d = -(f + n) / (f - n);
  4694. var i0 = (left + right) / (left - right);
  4695. var i1 = (top + bottom) / (bottom - top);
  4696. 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);
  4697. };
  4698. /**
  4699. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4700. */
  4701. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4702. var matrix = Matrix.Zero();
  4703. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4704. return matrix;
  4705. };
  4706. /**
  4707. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  4708. */
  4709. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4710. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4711. result.m[10] *= -1.0;
  4712. };
  4713. /**
  4714. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  4715. */
  4716. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4717. var matrix = Matrix.Zero();
  4718. var n = znear;
  4719. var f = zfar;
  4720. var a = 2.0 * n / width;
  4721. var b = 2.0 * n / height;
  4722. var c = (f + n) / (f - n);
  4723. var d = -2.0 * f * n / (f - n);
  4724. 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);
  4725. return matrix;
  4726. };
  4727. /**
  4728. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4729. */
  4730. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4731. var matrix = Matrix.Zero();
  4732. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4733. return matrix;
  4734. };
  4735. /**
  4736. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4737. */
  4738. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4739. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4740. var n = znear;
  4741. var f = zfar;
  4742. var t = 1.0 / (Math.tan(fov * 0.5));
  4743. var a = isVerticalFovFixed ? (t / aspect) : t;
  4744. var b = isVerticalFovFixed ? t : (t * aspect);
  4745. var c = (f + n) / (f - n);
  4746. var d = -2.0 * f * n / (f - n);
  4747. 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);
  4748. };
  4749. /**
  4750. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4751. */
  4752. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4753. var matrix = Matrix.Zero();
  4754. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4755. return matrix;
  4756. };
  4757. /**
  4758. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4759. */
  4760. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4761. //alternatively this could be expressed as:
  4762. // m = PerspectiveFovLHToRef
  4763. // m[10] *= -1.0;
  4764. // m[11] *= -1.0;
  4765. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4766. var n = znear;
  4767. var f = zfar;
  4768. var t = 1.0 / (Math.tan(fov * 0.5));
  4769. var a = isVerticalFovFixed ? (t / aspect) : t;
  4770. var b = isVerticalFovFixed ? t : (t * aspect);
  4771. var c = -(f + n) / (f - n);
  4772. var d = -2 * f * n / (f - n);
  4773. 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);
  4774. };
  4775. /**
  4776. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  4777. */
  4778. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4779. if (rightHanded === void 0) { rightHanded = false; }
  4780. var rightHandedFactor = rightHanded ? -1 : 1;
  4781. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4782. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4783. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4784. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4785. var xScale = 2.0 / (leftTan + rightTan);
  4786. var yScale = 2.0 / (upTan + downTan);
  4787. result.m[0] = xScale;
  4788. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4789. result.m[5] = yScale;
  4790. result.m[6] = result.m[7] = 0.0;
  4791. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4792. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4793. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4794. result.m[10] = -zfar / (znear - zfar);
  4795. result.m[11] = 1.0 * rightHandedFactor;
  4796. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4797. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4798. // result.m[14] = (znear * zfar) / (znear - zfar);
  4799. result._markAsUpdated();
  4800. };
  4801. /**
  4802. * Returns the final transformation matrix : world * view * projection * viewport
  4803. */
  4804. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4805. var cw = viewport.width;
  4806. var ch = viewport.height;
  4807. var cx = viewport.x;
  4808. var cy = viewport.y;
  4809. 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);
  4810. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4811. };
  4812. /**
  4813. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4814. */
  4815. Matrix.GetAsMatrix2x2 = function (matrix) {
  4816. return new Float32Array([
  4817. matrix.m[0], matrix.m[1],
  4818. matrix.m[4], matrix.m[5]
  4819. ]);
  4820. };
  4821. /**
  4822. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4823. */
  4824. Matrix.GetAsMatrix3x3 = function (matrix) {
  4825. return new Float32Array([
  4826. matrix.m[0], matrix.m[1], matrix.m[2],
  4827. matrix.m[4], matrix.m[5], matrix.m[6],
  4828. matrix.m[8], matrix.m[9], matrix.m[10]
  4829. ]);
  4830. };
  4831. /**
  4832. * Compute the transpose of the passed Matrix.
  4833. * Returns a new Matrix.
  4834. */
  4835. Matrix.Transpose = function (matrix) {
  4836. var result = new Matrix();
  4837. Matrix.TransposeToRef(matrix, result);
  4838. return result;
  4839. };
  4840. /**
  4841. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4842. */
  4843. Matrix.TransposeToRef = function (matrix, result) {
  4844. result.m[0] = matrix.m[0];
  4845. result.m[1] = matrix.m[4];
  4846. result.m[2] = matrix.m[8];
  4847. result.m[3] = matrix.m[12];
  4848. result.m[4] = matrix.m[1];
  4849. result.m[5] = matrix.m[5];
  4850. result.m[6] = matrix.m[9];
  4851. result.m[7] = matrix.m[13];
  4852. result.m[8] = matrix.m[2];
  4853. result.m[9] = matrix.m[6];
  4854. result.m[10] = matrix.m[10];
  4855. result.m[11] = matrix.m[14];
  4856. result.m[12] = matrix.m[3];
  4857. result.m[13] = matrix.m[7];
  4858. result.m[14] = matrix.m[11];
  4859. result.m[15] = matrix.m[15];
  4860. };
  4861. /**
  4862. * Returns a new Matrix as the reflection matrix across the passed plane.
  4863. */
  4864. Matrix.Reflection = function (plane) {
  4865. var matrix = new Matrix();
  4866. Matrix.ReflectionToRef(plane, matrix);
  4867. return matrix;
  4868. };
  4869. /**
  4870. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4871. */
  4872. Matrix.ReflectionToRef = function (plane, result) {
  4873. plane.normalize();
  4874. var x = plane.normal.x;
  4875. var y = plane.normal.y;
  4876. var z = plane.normal.z;
  4877. var temp = -2 * x;
  4878. var temp2 = -2 * y;
  4879. var temp3 = -2 * z;
  4880. result.m[0] = (temp * x) + 1;
  4881. result.m[1] = temp2 * x;
  4882. result.m[2] = temp3 * x;
  4883. result.m[3] = 0.0;
  4884. result.m[4] = temp * y;
  4885. result.m[5] = (temp2 * y) + 1;
  4886. result.m[6] = temp3 * y;
  4887. result.m[7] = 0.0;
  4888. result.m[8] = temp * z;
  4889. result.m[9] = temp2 * z;
  4890. result.m[10] = (temp3 * z) + 1;
  4891. result.m[11] = 0.0;
  4892. result.m[12] = temp * plane.d;
  4893. result.m[13] = temp2 * plane.d;
  4894. result.m[14] = temp3 * plane.d;
  4895. result.m[15] = 1.0;
  4896. result._markAsUpdated();
  4897. };
  4898. /**
  4899. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4900. */
  4901. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4902. result.m[0] = xaxis.x;
  4903. result.m[1] = xaxis.y;
  4904. result.m[2] = xaxis.z;
  4905. result.m[3] = 0.0;
  4906. result.m[4] = yaxis.x;
  4907. result.m[5] = yaxis.y;
  4908. result.m[6] = yaxis.z;
  4909. result.m[7] = 0.0;
  4910. result.m[8] = zaxis.x;
  4911. result.m[9] = zaxis.y;
  4912. result.m[10] = zaxis.z;
  4913. result.m[11] = 0.0;
  4914. result.m[12] = 0.0;
  4915. result.m[13] = 0.0;
  4916. result.m[14] = 0.0;
  4917. result.m[15] = 1.0;
  4918. result._markAsUpdated();
  4919. };
  4920. /**
  4921. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4922. */
  4923. Matrix.FromQuaternionToRef = function (quat, result) {
  4924. var xx = quat.x * quat.x;
  4925. var yy = quat.y * quat.y;
  4926. var zz = quat.z * quat.z;
  4927. var xy = quat.x * quat.y;
  4928. var zw = quat.z * quat.w;
  4929. var zx = quat.z * quat.x;
  4930. var yw = quat.y * quat.w;
  4931. var yz = quat.y * quat.z;
  4932. var xw = quat.x * quat.w;
  4933. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4934. result.m[1] = 2.0 * (xy + zw);
  4935. result.m[2] = 2.0 * (zx - yw);
  4936. result.m[3] = 0.0;
  4937. result.m[4] = 2.0 * (xy - zw);
  4938. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4939. result.m[6] = 2.0 * (yz + xw);
  4940. result.m[7] = 0.0;
  4941. result.m[8] = 2.0 * (zx + yw);
  4942. result.m[9] = 2.0 * (yz - xw);
  4943. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4944. result.m[11] = 0.0;
  4945. result.m[12] = 0.0;
  4946. result.m[13] = 0.0;
  4947. result.m[14] = 0.0;
  4948. result.m[15] = 1.0;
  4949. result._markAsUpdated();
  4950. };
  4951. Matrix._tempQuaternion = new Quaternion();
  4952. Matrix._xAxis = Vector3.Zero();
  4953. Matrix._yAxis = Vector3.Zero();
  4954. Matrix._zAxis = Vector3.Zero();
  4955. Matrix._updateFlagSeed = 0;
  4956. Matrix._identityReadOnly = Matrix.Identity();
  4957. return Matrix;
  4958. }());
  4959. BABYLON.Matrix = Matrix;
  4960. var Plane = /** @class */ (function () {
  4961. /**
  4962. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4963. */
  4964. function Plane(a, b, c, d) {
  4965. this.normal = new Vector3(a, b, c);
  4966. this.d = d;
  4967. }
  4968. /**
  4969. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4970. */
  4971. Plane.prototype.asArray = function () {
  4972. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4973. };
  4974. // Methods
  4975. /**
  4976. * Returns a new plane copied from the current Plane.
  4977. */
  4978. Plane.prototype.clone = function () {
  4979. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4980. };
  4981. /**
  4982. * Returns the string "Plane".
  4983. */
  4984. Plane.prototype.getClassName = function () {
  4985. return "Plane";
  4986. };
  4987. /**
  4988. * Returns the Plane hash code.
  4989. */
  4990. Plane.prototype.getHashCode = function () {
  4991. var hash = this.normal.getHashCode();
  4992. hash = (hash * 397) ^ (this.d || 0);
  4993. return hash;
  4994. };
  4995. /**
  4996. * Normalize the current Plane in place.
  4997. * Returns the updated Plane.
  4998. */
  4999. Plane.prototype.normalize = function () {
  5000. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5001. var magnitude = 0.0;
  5002. if (norm !== 0) {
  5003. magnitude = 1.0 / norm;
  5004. }
  5005. this.normal.x *= magnitude;
  5006. this.normal.y *= magnitude;
  5007. this.normal.z *= magnitude;
  5008. this.d *= magnitude;
  5009. return this;
  5010. };
  5011. /**
  5012. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5013. */
  5014. Plane.prototype.transform = function (transformation) {
  5015. var transposedMatrix = Matrix.Transpose(transformation);
  5016. var x = this.normal.x;
  5017. var y = this.normal.y;
  5018. var z = this.normal.z;
  5019. var d = this.d;
  5020. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5021. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5022. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5023. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5024. return new Plane(normalX, normalY, normalZ, finalD);
  5025. };
  5026. /**
  5027. * Returns the dot product (float) of the point coordinates and the plane normal.
  5028. */
  5029. Plane.prototype.dotCoordinate = function (point) {
  5030. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5031. };
  5032. /**
  5033. * Updates the current Plane from the plane defined by the three passed points.
  5034. * Returns the updated Plane.
  5035. */
  5036. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5037. var x1 = point2.x - point1.x;
  5038. var y1 = point2.y - point1.y;
  5039. var z1 = point2.z - point1.z;
  5040. var x2 = point3.x - point1.x;
  5041. var y2 = point3.y - point1.y;
  5042. var z2 = point3.z - point1.z;
  5043. var yz = (y1 * z2) - (z1 * y2);
  5044. var xz = (z1 * x2) - (x1 * z2);
  5045. var xy = (x1 * y2) - (y1 * x2);
  5046. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5047. var invPyth;
  5048. if (pyth !== 0) {
  5049. invPyth = 1.0 / pyth;
  5050. }
  5051. else {
  5052. invPyth = 0.0;
  5053. }
  5054. this.normal.x = yz * invPyth;
  5055. this.normal.y = xz * invPyth;
  5056. this.normal.z = xy * invPyth;
  5057. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5058. return this;
  5059. };
  5060. /**
  5061. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5062. */
  5063. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5064. var dot = Vector3.Dot(this.normal, direction);
  5065. return (dot <= epsilon);
  5066. };
  5067. /**
  5068. * Returns the signed distance (float) from the passed point to the Plane.
  5069. */
  5070. Plane.prototype.signedDistanceTo = function (point) {
  5071. return Vector3.Dot(point, this.normal) + this.d;
  5072. };
  5073. // Statics
  5074. /**
  5075. * Returns a new Plane from the passed array.
  5076. */
  5077. Plane.FromArray = function (array) {
  5078. return new Plane(array[0], array[1], array[2], array[3]);
  5079. };
  5080. /**
  5081. * Returns a new Plane defined by the three passed points.
  5082. */
  5083. Plane.FromPoints = function (point1, point2, point3) {
  5084. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5085. result.copyFromPoints(point1, point2, point3);
  5086. return result;
  5087. };
  5088. /**
  5089. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5090. * Note : the vector "normal" is updated because normalized.
  5091. */
  5092. Plane.FromPositionAndNormal = function (origin, normal) {
  5093. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5094. normal.normalize();
  5095. result.normal = normal;
  5096. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5097. return result;
  5098. };
  5099. /**
  5100. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5101. */
  5102. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5103. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5104. return Vector3.Dot(point, normal) + d;
  5105. };
  5106. return Plane;
  5107. }());
  5108. BABYLON.Plane = Plane;
  5109. var Viewport = /** @class */ (function () {
  5110. /**
  5111. * Creates a Viewport object located at (x, y) and sized (width, height).
  5112. */
  5113. function Viewport(x, y, width, height) {
  5114. this.x = x;
  5115. this.y = y;
  5116. this.width = width;
  5117. this.height = height;
  5118. }
  5119. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5120. if (renderWidthOrEngine.getRenderWidth) {
  5121. var engine = renderWidthOrEngine;
  5122. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5123. }
  5124. var renderWidth = renderWidthOrEngine;
  5125. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5126. };
  5127. /**
  5128. * Returns a new Viewport copied from the current one.
  5129. */
  5130. Viewport.prototype.clone = function () {
  5131. return new Viewport(this.x, this.y, this.width, this.height);
  5132. };
  5133. return Viewport;
  5134. }());
  5135. BABYLON.Viewport = Viewport;
  5136. var Frustum = /** @class */ (function () {
  5137. function Frustum() {
  5138. }
  5139. /**
  5140. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5141. */
  5142. Frustum.GetPlanes = function (transform) {
  5143. var frustumPlanes = [];
  5144. for (var index = 0; index < 6; index++) {
  5145. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5146. }
  5147. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5148. return frustumPlanes;
  5149. };
  5150. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5151. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5152. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5153. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5154. frustumPlane.d = transform.m[15] + transform.m[14];
  5155. frustumPlane.normalize();
  5156. };
  5157. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5158. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5159. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5160. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5161. frustumPlane.d = transform.m[15] - transform.m[14];
  5162. frustumPlane.normalize();
  5163. };
  5164. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5165. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5166. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5167. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5168. frustumPlane.d = transform.m[15] + transform.m[12];
  5169. frustumPlane.normalize();
  5170. };
  5171. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5172. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5173. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5174. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5175. frustumPlane.d = transform.m[15] - transform.m[12];
  5176. frustumPlane.normalize();
  5177. };
  5178. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5179. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5180. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5181. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5182. frustumPlane.d = transform.m[15] - transform.m[13];
  5183. frustumPlane.normalize();
  5184. };
  5185. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5186. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5187. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5188. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5189. frustumPlane.d = transform.m[15] + transform.m[13];
  5190. frustumPlane.normalize();
  5191. };
  5192. /**
  5193. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5194. */
  5195. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5196. // Near
  5197. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5198. // Far
  5199. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5200. // Left
  5201. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5202. // Right
  5203. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5204. // Top
  5205. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5206. // Bottom
  5207. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5208. };
  5209. return Frustum;
  5210. }());
  5211. BABYLON.Frustum = Frustum;
  5212. var Space;
  5213. (function (Space) {
  5214. Space[Space["LOCAL"] = 0] = "LOCAL";
  5215. Space[Space["WORLD"] = 1] = "WORLD";
  5216. Space[Space["BONE"] = 2] = "BONE";
  5217. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5218. var Axis = /** @class */ (function () {
  5219. function Axis() {
  5220. }
  5221. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5222. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5223. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5224. return Axis;
  5225. }());
  5226. BABYLON.Axis = Axis;
  5227. ;
  5228. var BezierCurve = /** @class */ (function () {
  5229. function BezierCurve() {
  5230. }
  5231. /**
  5232. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5233. */
  5234. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5235. // Extract X (which is equal to time here)
  5236. var f0 = 1 - 3 * x2 + 3 * x1;
  5237. var f1 = 3 * x2 - 6 * x1;
  5238. var f2 = 3 * x1;
  5239. var refinedT = t;
  5240. for (var i = 0; i < 5; i++) {
  5241. var refinedT2 = refinedT * refinedT;
  5242. var refinedT3 = refinedT2 * refinedT;
  5243. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5244. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5245. refinedT -= (x - t) * slope;
  5246. refinedT = Math.min(1, Math.max(0, refinedT));
  5247. }
  5248. // Resolve cubic bezier for the given x
  5249. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5250. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5251. Math.pow(refinedT, 3);
  5252. };
  5253. return BezierCurve;
  5254. }());
  5255. BABYLON.BezierCurve = BezierCurve;
  5256. var Orientation;
  5257. (function (Orientation) {
  5258. Orientation[Orientation["CW"] = 0] = "CW";
  5259. Orientation[Orientation["CCW"] = 1] = "CCW";
  5260. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5261. var Angle = /** @class */ (function () {
  5262. /**
  5263. * Creates an Angle object of "radians" radians (float).
  5264. */
  5265. function Angle(radians) {
  5266. var _this = this;
  5267. /**
  5268. * Returns the Angle value in degrees (float).
  5269. */
  5270. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5271. /**
  5272. * Returns the Angle value in radians (float).
  5273. */
  5274. this.radians = function () { return _this._radians; };
  5275. this._radians = radians;
  5276. if (this._radians < 0.0)
  5277. this._radians += (2.0 * Math.PI);
  5278. }
  5279. /**
  5280. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5281. */
  5282. Angle.BetweenTwoPoints = function (a, b) {
  5283. var delta = b.subtract(a);
  5284. var theta = Math.atan2(delta.y, delta.x);
  5285. return new Angle(theta);
  5286. };
  5287. /**
  5288. * Returns a new Angle object from the passed float in radians.
  5289. */
  5290. Angle.FromRadians = function (radians) {
  5291. return new Angle(radians);
  5292. };
  5293. /**
  5294. * Returns a new Angle object from the passed float in degrees.
  5295. */
  5296. Angle.FromDegrees = function (degrees) {
  5297. return new Angle(degrees * Math.PI / 180.0);
  5298. };
  5299. return Angle;
  5300. }());
  5301. BABYLON.Angle = Angle;
  5302. var Arc2 = /** @class */ (function () {
  5303. /**
  5304. * Creates an Arc object from the three passed points : start, middle and end.
  5305. */
  5306. function Arc2(startPoint, midPoint, endPoint) {
  5307. this.startPoint = startPoint;
  5308. this.midPoint = midPoint;
  5309. this.endPoint = endPoint;
  5310. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5311. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5312. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5313. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5314. 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);
  5315. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5316. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5317. var a1 = this.startAngle.degrees();
  5318. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5319. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5320. // angles correction
  5321. if (a2 - a1 > +180.0)
  5322. a2 -= 360.0;
  5323. if (a2 - a1 < -180.0)
  5324. a2 += 360.0;
  5325. if (a3 - a2 > +180.0)
  5326. a3 -= 360.0;
  5327. if (a3 - a2 < -180.0)
  5328. a3 += 360.0;
  5329. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5330. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5331. }
  5332. return Arc2;
  5333. }());
  5334. BABYLON.Arc2 = Arc2;
  5335. var Path2 = /** @class */ (function () {
  5336. /**
  5337. * Creates a Path2 object from the starting 2D coordinates x and y.
  5338. */
  5339. function Path2(x, y) {
  5340. this._points = new Array();
  5341. this._length = 0.0;
  5342. this.closed = false;
  5343. this._points.push(new Vector2(x, y));
  5344. }
  5345. /**
  5346. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5347. * Returns the updated Path2.
  5348. */
  5349. Path2.prototype.addLineTo = function (x, y) {
  5350. if (this.closed) {
  5351. //Tools.Error("cannot add lines to closed paths");
  5352. return this;
  5353. }
  5354. var newPoint = new Vector2(x, y);
  5355. var previousPoint = this._points[this._points.length - 1];
  5356. this._points.push(newPoint);
  5357. this._length += newPoint.subtract(previousPoint).length();
  5358. return this;
  5359. };
  5360. /**
  5361. * 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.
  5362. * Returns the updated Path2.
  5363. */
  5364. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5365. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5366. if (this.closed) {
  5367. //Tools.Error("cannot add arcs to closed paths");
  5368. return this;
  5369. }
  5370. var startPoint = this._points[this._points.length - 1];
  5371. var midPoint = new Vector2(midX, midY);
  5372. var endPoint = new Vector2(endX, endY);
  5373. var arc = new Arc2(startPoint, midPoint, endPoint);
  5374. var increment = arc.angle.radians() / numberOfSegments;
  5375. if (arc.orientation === Orientation.CW)
  5376. increment *= -1;
  5377. var currentAngle = arc.startAngle.radians() + increment;
  5378. for (var i = 0; i < numberOfSegments; i++) {
  5379. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5380. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5381. this.addLineTo(x, y);
  5382. currentAngle += increment;
  5383. }
  5384. return this;
  5385. };
  5386. /**
  5387. * Closes the Path2.
  5388. * Returns the Path2.
  5389. */
  5390. Path2.prototype.close = function () {
  5391. this.closed = true;
  5392. return this;
  5393. };
  5394. /**
  5395. * Returns the Path2 total length (float).
  5396. */
  5397. Path2.prototype.length = function () {
  5398. var result = this._length;
  5399. if (!this.closed) {
  5400. var lastPoint = this._points[this._points.length - 1];
  5401. var firstPoint = this._points[0];
  5402. result += (firstPoint.subtract(lastPoint).length());
  5403. }
  5404. return result;
  5405. };
  5406. /**
  5407. * Returns the Path2 internal array of points.
  5408. */
  5409. Path2.prototype.getPoints = function () {
  5410. return this._points;
  5411. };
  5412. /**
  5413. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5414. */
  5415. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5416. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5417. //Tools.Error("normalized length position should be between 0 and 1.");
  5418. return Vector2.Zero();
  5419. }
  5420. var lengthPosition = normalizedLengthPosition * this.length();
  5421. var previousOffset = 0;
  5422. for (var i = 0; i < this._points.length; i++) {
  5423. var j = (i + 1) % this._points.length;
  5424. var a = this._points[i];
  5425. var b = this._points[j];
  5426. var bToA = b.subtract(a);
  5427. var nextOffset = (bToA.length() + previousOffset);
  5428. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5429. var dir = bToA.normalize();
  5430. var localOffset = lengthPosition - previousOffset;
  5431. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5432. }
  5433. previousOffset = nextOffset;
  5434. }
  5435. //Tools.Error("internal error");
  5436. return Vector2.Zero();
  5437. };
  5438. /**
  5439. * Returns a new Path2 starting at the coordinates (x, y).
  5440. */
  5441. Path2.StartingAt = function (x, y) {
  5442. return new Path2(x, y);
  5443. };
  5444. return Path2;
  5445. }());
  5446. BABYLON.Path2 = Path2;
  5447. var Path3D = /** @class */ (function () {
  5448. /**
  5449. * new Path3D(path, normal, raw)
  5450. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5451. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5452. * path : an array of Vector3, the curve axis of the Path3D
  5453. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5454. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5455. */
  5456. function Path3D(path, firstNormal, raw) {
  5457. if (firstNormal === void 0) { firstNormal = null; }
  5458. this.path = path;
  5459. this._curve = new Array();
  5460. this._distances = new Array();
  5461. this._tangents = new Array();
  5462. this._normals = new Array();
  5463. this._binormals = new Array();
  5464. for (var p = 0; p < path.length; p++) {
  5465. this._curve[p] = path[p].clone(); // hard copy
  5466. }
  5467. this._raw = raw || false;
  5468. this._compute(firstNormal);
  5469. }
  5470. /**
  5471. * Returns the Path3D array of successive Vector3 designing its curve.
  5472. */
  5473. Path3D.prototype.getCurve = function () {
  5474. return this._curve;
  5475. };
  5476. /**
  5477. * Returns an array populated with tangent vectors on each Path3D curve point.
  5478. */
  5479. Path3D.prototype.getTangents = function () {
  5480. return this._tangents;
  5481. };
  5482. /**
  5483. * Returns an array populated with normal vectors on each Path3D curve point.
  5484. */
  5485. Path3D.prototype.getNormals = function () {
  5486. return this._normals;
  5487. };
  5488. /**
  5489. * Returns an array populated with binormal vectors on each Path3D curve point.
  5490. */
  5491. Path3D.prototype.getBinormals = function () {
  5492. return this._binormals;
  5493. };
  5494. /**
  5495. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5496. */
  5497. Path3D.prototype.getDistances = function () {
  5498. return this._distances;
  5499. };
  5500. /**
  5501. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5502. * Returns the same object updated.
  5503. */
  5504. Path3D.prototype.update = function (path, firstNormal) {
  5505. if (firstNormal === void 0) { firstNormal = null; }
  5506. for (var p = 0; p < path.length; p++) {
  5507. this._curve[p].x = path[p].x;
  5508. this._curve[p].y = path[p].y;
  5509. this._curve[p].z = path[p].z;
  5510. }
  5511. this._compute(firstNormal);
  5512. return this;
  5513. };
  5514. // private function compute() : computes tangents, normals and binormals
  5515. Path3D.prototype._compute = function (firstNormal) {
  5516. var l = this._curve.length;
  5517. // first and last tangents
  5518. this._tangents[0] = this._getFirstNonNullVector(0);
  5519. if (!this._raw) {
  5520. this._tangents[0].normalize();
  5521. }
  5522. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5523. if (!this._raw) {
  5524. this._tangents[l - 1].normalize();
  5525. }
  5526. // normals and binormals at first point : arbitrary vector with _normalVector()
  5527. var tg0 = this._tangents[0];
  5528. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5529. this._normals[0] = pp0;
  5530. if (!this._raw) {
  5531. this._normals[0].normalize();
  5532. }
  5533. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5534. if (!this._raw) {
  5535. this._binormals[0].normalize();
  5536. }
  5537. this._distances[0] = 0.0;
  5538. // normals and binormals : next points
  5539. var prev; // previous vector (segment)
  5540. var cur; // current vector (segment)
  5541. var curTang; // current tangent
  5542. // previous normal
  5543. var prevBinor; // previous binormal
  5544. for (var i = 1; i < l; i++) {
  5545. // tangents
  5546. prev = this._getLastNonNullVector(i);
  5547. if (i < l - 1) {
  5548. cur = this._getFirstNonNullVector(i);
  5549. this._tangents[i] = prev.add(cur);
  5550. this._tangents[i].normalize();
  5551. }
  5552. this._distances[i] = this._distances[i - 1] + prev.length();
  5553. // normals and binormals
  5554. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5555. curTang = this._tangents[i];
  5556. prevBinor = this._binormals[i - 1];
  5557. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5558. if (!this._raw) {
  5559. this._normals[i].normalize();
  5560. }
  5561. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5562. if (!this._raw) {
  5563. this._binormals[i].normalize();
  5564. }
  5565. }
  5566. };
  5567. // private function getFirstNonNullVector(index)
  5568. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5569. Path3D.prototype._getFirstNonNullVector = function (index) {
  5570. var i = 1;
  5571. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5572. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5573. i++;
  5574. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5575. }
  5576. return nNVector;
  5577. };
  5578. // private function getLastNonNullVector(index)
  5579. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5580. Path3D.prototype._getLastNonNullVector = function (index) {
  5581. var i = 1;
  5582. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5583. while (nLVector.length() === 0 && index > i + 1) {
  5584. i++;
  5585. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5586. }
  5587. return nLVector;
  5588. };
  5589. // private function normalVector(v0, vt, va) :
  5590. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5591. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5592. Path3D.prototype._normalVector = function (v0, vt, va) {
  5593. var normal0;
  5594. var tgl = vt.length();
  5595. if (tgl === 0.0) {
  5596. tgl = 1.0;
  5597. }
  5598. if (va === undefined || va === null) {
  5599. var point;
  5600. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5601. point = new Vector3(0.0, -1.0, 0.0);
  5602. }
  5603. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5604. point = new Vector3(1.0, 0.0, 0.0);
  5605. }
  5606. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5607. point = new Vector3(0.0, 0.0, 1.0);
  5608. }
  5609. else {
  5610. point = Vector3.Zero();
  5611. }
  5612. normal0 = Vector3.Cross(vt, point);
  5613. }
  5614. else {
  5615. normal0 = Vector3.Cross(vt, va);
  5616. Vector3.CrossToRef(normal0, vt, normal0);
  5617. }
  5618. normal0.normalize();
  5619. return normal0;
  5620. };
  5621. return Path3D;
  5622. }());
  5623. BABYLON.Path3D = Path3D;
  5624. var Curve3 = /** @class */ (function () {
  5625. /**
  5626. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5627. * A Curve3 is designed from a series of successive Vector3.
  5628. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5629. */
  5630. function Curve3(points) {
  5631. this._length = 0.0;
  5632. this._points = points;
  5633. this._length = this._computeLength(points);
  5634. }
  5635. /**
  5636. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5637. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5638. * @param v1 (Vector3) the control point
  5639. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5640. * @param nbPoints (integer) the wanted number of points in the curve
  5641. */
  5642. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5643. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5644. var bez = new Array();
  5645. var equation = function (t, val0, val1, val2) {
  5646. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5647. return res;
  5648. };
  5649. for (var i = 0; i <= nbPoints; i++) {
  5650. 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)));
  5651. }
  5652. return new Curve3(bez);
  5653. };
  5654. /**
  5655. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5656. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5657. * @param v1 (Vector3) the first control point
  5658. * @param v2 (Vector3) the second control point
  5659. * @param v3 (Vector3) the end point of the Cubic Bezier
  5660. * @param nbPoints (integer) the wanted number of points in the curve
  5661. */
  5662. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5663. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5664. var bez = new Array();
  5665. var equation = function (t, val0, val1, val2, val3) {
  5666. 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;
  5667. return res;
  5668. };
  5669. for (var i = 0; i <= nbPoints; i++) {
  5670. 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)));
  5671. }
  5672. return new Curve3(bez);
  5673. };
  5674. /**
  5675. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5676. * @param p1 (Vector3) the origin point of the Hermite Spline
  5677. * @param t1 (Vector3) the tangent vector at the origin point
  5678. * @param p2 (Vector3) the end point of the Hermite Spline
  5679. * @param t2 (Vector3) the tangent vector at the end point
  5680. * @param nbPoints (integer) the wanted number of points in the curve
  5681. */
  5682. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5683. var hermite = new Array();
  5684. var step = 1.0 / nbPoints;
  5685. for (var i = 0; i <= nbPoints; i++) {
  5686. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5687. }
  5688. return new Curve3(hermite);
  5689. };
  5690. /**
  5691. * Returns a Curve3 object along a CatmullRom Spline curve :
  5692. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5693. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5694. */
  5695. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5696. var totalPoints = new Array();
  5697. totalPoints.push(points[0].clone());
  5698. Array.prototype.push.apply(totalPoints, points);
  5699. totalPoints.push(points[points.length - 1].clone());
  5700. var catmullRom = new Array();
  5701. var step = 1.0 / nbPoints;
  5702. var amount = 0.0;
  5703. for (var i = 0; i < totalPoints.length - 3; i++) {
  5704. amount = 0;
  5705. for (var c = 0; c < nbPoints; c++) {
  5706. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5707. amount += step;
  5708. }
  5709. }
  5710. i--;
  5711. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5712. return new Curve3(catmullRom);
  5713. };
  5714. /**
  5715. * Returns the Curve3 stored array of successive Vector3
  5716. */
  5717. Curve3.prototype.getPoints = function () {
  5718. return this._points;
  5719. };
  5720. /**
  5721. * Returns the computed length (float) of the curve.
  5722. */
  5723. Curve3.prototype.length = function () {
  5724. return this._length;
  5725. };
  5726. /**
  5727. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5728. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5729. * curveA and curveB keep unchanged.
  5730. */
  5731. Curve3.prototype.continue = function (curve) {
  5732. var lastPoint = this._points[this._points.length - 1];
  5733. var continuedPoints = this._points.slice();
  5734. var curvePoints = curve.getPoints();
  5735. for (var i = 1; i < curvePoints.length; i++) {
  5736. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5737. }
  5738. var continuedCurve = new Curve3(continuedPoints);
  5739. return continuedCurve;
  5740. };
  5741. Curve3.prototype._computeLength = function (path) {
  5742. var l = 0;
  5743. for (var i = 1; i < path.length; i++) {
  5744. l += (path[i].subtract(path[i - 1])).length();
  5745. }
  5746. return l;
  5747. };
  5748. return Curve3;
  5749. }());
  5750. BABYLON.Curve3 = Curve3;
  5751. // Vertex formats
  5752. var PositionNormalVertex = /** @class */ (function () {
  5753. function PositionNormalVertex(position, normal) {
  5754. if (position === void 0) { position = Vector3.Zero(); }
  5755. if (normal === void 0) { normal = Vector3.Up(); }
  5756. this.position = position;
  5757. this.normal = normal;
  5758. }
  5759. PositionNormalVertex.prototype.clone = function () {
  5760. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5761. };
  5762. return PositionNormalVertex;
  5763. }());
  5764. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5765. var PositionNormalTextureVertex = /** @class */ (function () {
  5766. function PositionNormalTextureVertex(position, normal, uv) {
  5767. if (position === void 0) { position = Vector3.Zero(); }
  5768. if (normal === void 0) { normal = Vector3.Up(); }
  5769. if (uv === void 0) { uv = Vector2.Zero(); }
  5770. this.position = position;
  5771. this.normal = normal;
  5772. this.uv = uv;
  5773. }
  5774. PositionNormalTextureVertex.prototype.clone = function () {
  5775. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5776. };
  5777. return PositionNormalTextureVertex;
  5778. }());
  5779. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5780. // Temporary pre-allocated objects for engine internal use
  5781. // usage in any internal function :
  5782. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5783. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5784. var Tmp = /** @class */ (function () {
  5785. function Tmp() {
  5786. }
  5787. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5788. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5789. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5790. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5791. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5792. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5793. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5794. Matrix.Zero(), Matrix.Zero(),
  5795. Matrix.Zero(), Matrix.Zero(),
  5796. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5797. return Tmp;
  5798. }());
  5799. BABYLON.Tmp = Tmp;
  5800. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5801. var MathTmp = /** @class */ (function () {
  5802. function MathTmp() {
  5803. }
  5804. MathTmp.Vector3 = [Vector3.Zero()];
  5805. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5806. MathTmp.Quaternion = [Quaternion.Zero()];
  5807. return MathTmp;
  5808. }());
  5809. })(BABYLON || (BABYLON = {}));
  5810. //# sourceMappingURL=babylon.math.js.map
  5811. var BABYLON;
  5812. (function (BABYLON) {
  5813. var Scalar = /** @class */ (function () {
  5814. function Scalar() {
  5815. }
  5816. /**
  5817. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5818. */
  5819. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5820. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5821. var num = a - b;
  5822. return -epsilon <= num && num <= epsilon;
  5823. };
  5824. /**
  5825. * Returns a string : the upper case translation of the number i to hexadecimal.
  5826. */
  5827. Scalar.ToHex = function (i) {
  5828. var str = i.toString(16);
  5829. if (i <= 15) {
  5830. return ("0" + str).toUpperCase();
  5831. }
  5832. return str.toUpperCase();
  5833. };
  5834. /**
  5835. * Returns -1 if value is negative and +1 is value is positive.
  5836. * Returns the value itself if it's equal to zero.
  5837. */
  5838. Scalar.Sign = function (value) {
  5839. value = +value; // convert to a number
  5840. if (value === 0 || isNaN(value))
  5841. return value;
  5842. return value > 0 ? 1 : -1;
  5843. };
  5844. /**
  5845. * Returns the value itself if it's between min and max.
  5846. * Returns min if the value is lower than min.
  5847. * Returns max if the value is greater than max.
  5848. */
  5849. Scalar.Clamp = function (value, min, max) {
  5850. if (min === void 0) { min = 0; }
  5851. if (max === void 0) { max = 1; }
  5852. return Math.min(max, Math.max(min, value));
  5853. };
  5854. /**
  5855. * Returns the log2 of value.
  5856. */
  5857. Scalar.Log2 = function (value) {
  5858. return Math.log(value) * Math.LOG2E;
  5859. };
  5860. /**
  5861. * Loops the value, so that it is never larger than length and never smaller than 0.
  5862. *
  5863. * This is similar to the modulo operator but it works with floating point numbers.
  5864. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5865. * With t = 5 and length = 2.5, the result would be 0.0.
  5866. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5867. */
  5868. Scalar.Repeat = function (value, length) {
  5869. return value - Math.floor(value / length) * length;
  5870. };
  5871. /**
  5872. * Normalize the value between 0.0 and 1.0 using min and max values
  5873. */
  5874. Scalar.Normalize = function (value, min, max) {
  5875. return (value - min) / (max - min);
  5876. };
  5877. /**
  5878. * Denormalize the value from 0.0 and 1.0 using min and max values
  5879. */
  5880. Scalar.Denormalize = function (normalized, min, max) {
  5881. return (normalized * (max - min) + min);
  5882. };
  5883. /**
  5884. * Calculates the shortest difference between two given angles given in degrees.
  5885. */
  5886. Scalar.DeltaAngle = function (current, target) {
  5887. var num = Scalar.Repeat(target - current, 360.0);
  5888. if (num > 180.0) {
  5889. num -= 360.0;
  5890. }
  5891. return num;
  5892. };
  5893. /**
  5894. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5895. *
  5896. * The returned value will move back and forth between 0 and length
  5897. */
  5898. Scalar.PingPong = function (tx, length) {
  5899. var t = Scalar.Repeat(tx, length * 2.0);
  5900. return length - Math.abs(t - length);
  5901. };
  5902. /**
  5903. * Interpolates between min and max with smoothing at the limits.
  5904. *
  5905. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5906. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5907. */
  5908. Scalar.SmoothStep = function (from, to, tx) {
  5909. var t = Scalar.Clamp(tx);
  5910. t = -2.0 * t * t * t + 3.0 * t * t;
  5911. return to * t + from * (1.0 - t);
  5912. };
  5913. /**
  5914. * Moves a value current towards target.
  5915. *
  5916. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5917. * Negative values of maxDelta pushes the value away from target.
  5918. */
  5919. Scalar.MoveTowards = function (current, target, maxDelta) {
  5920. var result = 0;
  5921. if (Math.abs(target - current) <= maxDelta) {
  5922. result = target;
  5923. }
  5924. else {
  5925. result = current + Scalar.Sign(target - current) * maxDelta;
  5926. }
  5927. return result;
  5928. };
  5929. /**
  5930. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5931. *
  5932. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5933. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5934. */
  5935. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5936. var num = Scalar.DeltaAngle(current, target);
  5937. var result = 0;
  5938. if (-maxDelta < num && num < maxDelta) {
  5939. result = target;
  5940. }
  5941. else {
  5942. target = current + num;
  5943. result = Scalar.MoveTowards(current, target, maxDelta);
  5944. }
  5945. return result;
  5946. };
  5947. /**
  5948. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5949. */
  5950. Scalar.Lerp = function (start, end, amount) {
  5951. return start + ((end - start) * amount);
  5952. };
  5953. /**
  5954. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5955. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5956. */
  5957. Scalar.LerpAngle = function (start, end, amount) {
  5958. var num = Scalar.Repeat(end - start, 360.0);
  5959. if (num > 180.0) {
  5960. num -= 360.0;
  5961. }
  5962. return start + num * Scalar.Clamp(amount);
  5963. };
  5964. /**
  5965. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5966. */
  5967. Scalar.InverseLerp = function (a, b, value) {
  5968. var result = 0;
  5969. if (a != b) {
  5970. result = Scalar.Clamp((value - a) / (b - a));
  5971. }
  5972. else {
  5973. result = 0.0;
  5974. }
  5975. return result;
  5976. };
  5977. /**
  5978. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5979. */
  5980. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5981. var squared = amount * amount;
  5982. var cubed = amount * squared;
  5983. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5984. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5985. var part3 = (cubed - (2.0 * squared)) + amount;
  5986. var part4 = cubed - squared;
  5987. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5988. };
  5989. /**
  5990. * Returns a random float number between and min and max values
  5991. */
  5992. Scalar.RandomRange = function (min, max) {
  5993. if (min === max)
  5994. return min;
  5995. return ((Math.random() * (max - min)) + min);
  5996. };
  5997. /**
  5998. * This function returns percentage of a number in a given range.
  5999. *
  6000. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6001. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6002. */
  6003. Scalar.RangeToPercent = function (number, min, max) {
  6004. return ((number - min) / (max - min));
  6005. };
  6006. /**
  6007. * This function returns number that corresponds to the percentage in a given range.
  6008. *
  6009. * PercentToRange(0.34,0,100) will return 34.
  6010. */
  6011. Scalar.PercentToRange = function (percent, min, max) {
  6012. return ((max - min) * percent + min);
  6013. };
  6014. /**
  6015. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6016. * @param angle The angle to normalize in radian.
  6017. * @return The converted angle.
  6018. */
  6019. Scalar.NormalizeRadians = function (angle) {
  6020. // More precise but slower version kept for reference.
  6021. // angle = angle % Tools.TwoPi;
  6022. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6023. //if (angle > Math.PI) {
  6024. // angle -= Tools.TwoPi;
  6025. //}
  6026. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6027. return angle;
  6028. };
  6029. /**
  6030. * Two pi constants convenient for computation.
  6031. */
  6032. Scalar.TwoPi = Math.PI * 2;
  6033. return Scalar;
  6034. }());
  6035. BABYLON.Scalar = Scalar;
  6036. })(BABYLON || (BABYLON = {}));
  6037. //# sourceMappingURL=babylon.math.scalar.js.map
  6038. //# sourceMappingURL=babylon.mixins.js.map
  6039. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6040. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6041. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6042. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6043. //# sourceMappingURL=babylon.webgl2.js.map
  6044. var BABYLON;
  6045. (function (BABYLON) {
  6046. var __decoratorInitialStore = {};
  6047. var __mergedStore = {};
  6048. var _copySource = function (creationFunction, source, instanciate) {
  6049. var destination = creationFunction();
  6050. // Tags
  6051. if (BABYLON.Tags) {
  6052. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6053. }
  6054. var classStore = getMergedStore(destination);
  6055. // Properties
  6056. for (var property in classStore) {
  6057. var propertyDescriptor = classStore[property];
  6058. var sourceProperty = source[property];
  6059. var propertyType = propertyDescriptor.type;
  6060. if (sourceProperty !== undefined && sourceProperty !== null) {
  6061. switch (propertyType) {
  6062. case 0: // Value
  6063. case 6:// Mesh reference
  6064. destination[property] = sourceProperty;
  6065. break;
  6066. case 1:// Texture
  6067. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6068. break;
  6069. case 2: // Color3
  6070. case 3: // FresnelParameters
  6071. case 4: // Vector2
  6072. case 5: // Vector3
  6073. case 7: // Color Curves
  6074. case 10:// Quaternion
  6075. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6076. break;
  6077. }
  6078. }
  6079. }
  6080. return destination;
  6081. };
  6082. function getDirectStore(target) {
  6083. var classKey = target.getClassName();
  6084. if (!__decoratorInitialStore[classKey]) {
  6085. __decoratorInitialStore[classKey] = {};
  6086. }
  6087. return __decoratorInitialStore[classKey];
  6088. }
  6089. /**
  6090. * Return the list of properties flagged as serializable
  6091. * @param target: host object
  6092. */
  6093. function getMergedStore(target) {
  6094. var classKey = target.getClassName();
  6095. if (__mergedStore[classKey]) {
  6096. return __mergedStore[classKey];
  6097. }
  6098. __mergedStore[classKey] = {};
  6099. var store = __mergedStore[classKey];
  6100. var currentTarget = target;
  6101. var currentKey = classKey;
  6102. while (currentKey) {
  6103. var initialStore = __decoratorInitialStore[currentKey];
  6104. for (var property in initialStore) {
  6105. store[property] = initialStore[property];
  6106. }
  6107. var parent_1 = void 0;
  6108. var done = false;
  6109. do {
  6110. parent_1 = Object.getPrototypeOf(currentTarget);
  6111. if (!parent_1.getClassName) {
  6112. done = true;
  6113. break;
  6114. }
  6115. if (parent_1.getClassName() !== currentKey) {
  6116. break;
  6117. }
  6118. currentTarget = parent_1;
  6119. } while (parent_1);
  6120. if (done) {
  6121. break;
  6122. }
  6123. currentKey = parent_1.getClassName();
  6124. currentTarget = parent_1;
  6125. }
  6126. return store;
  6127. }
  6128. function generateSerializableMember(type, sourceName) {
  6129. return function (target, propertyKey) {
  6130. var classStore = getDirectStore(target);
  6131. if (!classStore[propertyKey]) {
  6132. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6133. }
  6134. };
  6135. }
  6136. function generateExpandMember(setCallback, targetKey) {
  6137. if (targetKey === void 0) { targetKey = null; }
  6138. return function (target, propertyKey) {
  6139. var key = targetKey || ("_" + propertyKey);
  6140. Object.defineProperty(target, propertyKey, {
  6141. get: function () {
  6142. return this[key];
  6143. },
  6144. set: function (value) {
  6145. if (this[key] === value) {
  6146. return;
  6147. }
  6148. this[key] = value;
  6149. target[setCallback].apply(this);
  6150. },
  6151. enumerable: true,
  6152. configurable: true
  6153. });
  6154. };
  6155. }
  6156. function expandToProperty(callback, targetKey) {
  6157. if (targetKey === void 0) { targetKey = null; }
  6158. return generateExpandMember(callback, targetKey);
  6159. }
  6160. BABYLON.expandToProperty = expandToProperty;
  6161. function serialize(sourceName) {
  6162. return generateSerializableMember(0, sourceName); // value member
  6163. }
  6164. BABYLON.serialize = serialize;
  6165. function serializeAsTexture(sourceName) {
  6166. return generateSerializableMember(1, sourceName); // texture member
  6167. }
  6168. BABYLON.serializeAsTexture = serializeAsTexture;
  6169. function serializeAsColor3(sourceName) {
  6170. return generateSerializableMember(2, sourceName); // color3 member
  6171. }
  6172. BABYLON.serializeAsColor3 = serializeAsColor3;
  6173. function serializeAsFresnelParameters(sourceName) {
  6174. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6175. }
  6176. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6177. function serializeAsVector2(sourceName) {
  6178. return generateSerializableMember(4, sourceName); // vector2 member
  6179. }
  6180. BABYLON.serializeAsVector2 = serializeAsVector2;
  6181. function serializeAsVector3(sourceName) {
  6182. return generateSerializableMember(5, sourceName); // vector3 member
  6183. }
  6184. BABYLON.serializeAsVector3 = serializeAsVector3;
  6185. function serializeAsMeshReference(sourceName) {
  6186. return generateSerializableMember(6, sourceName); // mesh reference member
  6187. }
  6188. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6189. function serializeAsColorCurves(sourceName) {
  6190. return generateSerializableMember(7, sourceName); // color curves
  6191. }
  6192. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6193. function serializeAsColor4(sourceName) {
  6194. return generateSerializableMember(8, sourceName); // color 4
  6195. }
  6196. BABYLON.serializeAsColor4 = serializeAsColor4;
  6197. function serializeAsImageProcessingConfiguration(sourceName) {
  6198. return generateSerializableMember(9, sourceName); // image processing
  6199. }
  6200. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6201. function serializeAsQuaternion(sourceName) {
  6202. return generateSerializableMember(10, sourceName); // quaternion member
  6203. }
  6204. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6205. var SerializationHelper = /** @class */ (function () {
  6206. function SerializationHelper() {
  6207. }
  6208. SerializationHelper.Serialize = function (entity, serializationObject) {
  6209. if (!serializationObject) {
  6210. serializationObject = {};
  6211. }
  6212. // Tags
  6213. if (BABYLON.Tags) {
  6214. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6215. }
  6216. var serializedProperties = getMergedStore(entity);
  6217. // Properties
  6218. for (var property in serializedProperties) {
  6219. var propertyDescriptor = serializedProperties[property];
  6220. var targetPropertyName = propertyDescriptor.sourceName || property;
  6221. var propertyType = propertyDescriptor.type;
  6222. var sourceProperty = entity[property];
  6223. if (sourceProperty !== undefined && sourceProperty !== null) {
  6224. switch (propertyType) {
  6225. case 0:// Value
  6226. serializationObject[targetPropertyName] = sourceProperty;
  6227. break;
  6228. case 1:// Texture
  6229. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6230. break;
  6231. case 2:// Color3
  6232. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6233. break;
  6234. case 3:// FresnelParameters
  6235. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6236. break;
  6237. case 4:// Vector2
  6238. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6239. break;
  6240. case 5:// Vector3
  6241. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6242. break;
  6243. case 6:// Mesh reference
  6244. serializationObject[targetPropertyName] = sourceProperty.id;
  6245. break;
  6246. case 7:// Color Curves
  6247. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6248. break;
  6249. case 8:// Color 4
  6250. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6251. break;
  6252. case 9:// Image Processing
  6253. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6254. break;
  6255. }
  6256. }
  6257. }
  6258. return serializationObject;
  6259. };
  6260. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6261. if (rootUrl === void 0) { rootUrl = null; }
  6262. var destination = creationFunction();
  6263. if (!rootUrl) {
  6264. rootUrl = "";
  6265. }
  6266. // Tags
  6267. if (BABYLON.Tags) {
  6268. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6269. }
  6270. var classStore = getMergedStore(destination);
  6271. // Properties
  6272. for (var property in classStore) {
  6273. var propertyDescriptor = classStore[property];
  6274. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6275. var propertyType = propertyDescriptor.type;
  6276. if (sourceProperty !== undefined && sourceProperty !== null) {
  6277. var dest = destination;
  6278. switch (propertyType) {
  6279. case 0:// Value
  6280. dest[property] = sourceProperty;
  6281. break;
  6282. case 1:// Texture
  6283. if (scene) {
  6284. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6285. }
  6286. break;
  6287. case 2:// Color3
  6288. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6289. break;
  6290. case 3:// FresnelParameters
  6291. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6292. break;
  6293. case 4:// Vector2
  6294. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6295. break;
  6296. case 5:// Vector3
  6297. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6298. break;
  6299. case 6:// Mesh reference
  6300. if (scene) {
  6301. dest[property] = scene.getLastMeshByID(sourceProperty);
  6302. }
  6303. break;
  6304. case 7:// Color Curves
  6305. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6306. break;
  6307. case 8:// Color 4
  6308. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6309. break;
  6310. case 9:// Image Processing
  6311. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6312. break;
  6313. }
  6314. }
  6315. }
  6316. return destination;
  6317. };
  6318. SerializationHelper.Clone = function (creationFunction, source) {
  6319. return _copySource(creationFunction, source, false);
  6320. };
  6321. SerializationHelper.Instanciate = function (creationFunction, source) {
  6322. return _copySource(creationFunction, source, true);
  6323. };
  6324. return SerializationHelper;
  6325. }());
  6326. BABYLON.SerializationHelper = SerializationHelper;
  6327. })(BABYLON || (BABYLON = {}));
  6328. //# sourceMappingURL=babylon.decorators.js.map
  6329. var BABYLON;
  6330. (function (BABYLON) {
  6331. /**
  6332. * A class serves as a medium between the observable and its observers
  6333. */
  6334. var EventState = /** @class */ (function () {
  6335. /**
  6336. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6337. */
  6338. function EventState(mask, skipNextObservers, target, currentTarget) {
  6339. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6340. this.initalize(mask, skipNextObservers, target, currentTarget);
  6341. }
  6342. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6343. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6344. this.mask = mask;
  6345. this.skipNextObservers = skipNextObservers;
  6346. this.target = target;
  6347. this.currentTarget = currentTarget;
  6348. return this;
  6349. };
  6350. return EventState;
  6351. }());
  6352. BABYLON.EventState = EventState;
  6353. /**
  6354. * Represent an Observer registered to a given Observable object.
  6355. */
  6356. var Observer = /** @class */ (function () {
  6357. function Observer(callback, mask, scope) {
  6358. if (scope === void 0) { scope = null; }
  6359. this.callback = callback;
  6360. this.mask = mask;
  6361. this.scope = scope;
  6362. }
  6363. return Observer;
  6364. }());
  6365. BABYLON.Observer = Observer;
  6366. /**
  6367. * Represent a list of observers registered to multiple Observables object.
  6368. */
  6369. var MultiObserver = /** @class */ (function () {
  6370. function MultiObserver() {
  6371. }
  6372. MultiObserver.prototype.dispose = function () {
  6373. if (this._observers && this._observables) {
  6374. for (var index = 0; index < this._observers.length; index++) {
  6375. this._observables[index].remove(this._observers[index]);
  6376. }
  6377. }
  6378. this._observers = null;
  6379. this._observables = null;
  6380. };
  6381. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6382. if (mask === void 0) { mask = -1; }
  6383. if (scope === void 0) { scope = null; }
  6384. var result = new MultiObserver();
  6385. result._observers = new Array();
  6386. result._observables = observables;
  6387. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6388. var observable = observables_1[_i];
  6389. var observer = observable.add(callback, mask, false, scope);
  6390. if (observer) {
  6391. result._observers.push(observer);
  6392. }
  6393. }
  6394. return result;
  6395. };
  6396. return MultiObserver;
  6397. }());
  6398. BABYLON.MultiObserver = MultiObserver;
  6399. /**
  6400. * The Observable class is a simple implementation of the Observable pattern.
  6401. * 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.
  6402. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6403. * 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).
  6404. * 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.
  6405. */
  6406. var Observable = /** @class */ (function () {
  6407. function Observable(onObserverAdded) {
  6408. this._observers = new Array();
  6409. this._eventState = new EventState(0);
  6410. if (onObserverAdded) {
  6411. this._onObserverAdded = onObserverAdded;
  6412. }
  6413. }
  6414. /**
  6415. * Create a new Observer with the specified callback
  6416. * @param callback the callback that will be executed for that Observer
  6417. * @param mask the mask used to filter observers
  6418. * @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.
  6419. * @param scope optional scope for the callback to be called from
  6420. */
  6421. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6422. if (mask === void 0) { mask = -1; }
  6423. if (insertFirst === void 0) { insertFirst = false; }
  6424. if (scope === void 0) { scope = null; }
  6425. if (!callback) {
  6426. return null;
  6427. }
  6428. var observer = new Observer(callback, mask, scope);
  6429. if (insertFirst) {
  6430. this._observers.unshift(observer);
  6431. }
  6432. else {
  6433. this._observers.push(observer);
  6434. }
  6435. if (this._onObserverAdded) {
  6436. this._onObserverAdded(observer);
  6437. }
  6438. return observer;
  6439. };
  6440. /**
  6441. * Remove an Observer from the Observable object
  6442. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6443. */
  6444. Observable.prototype.remove = function (observer) {
  6445. if (!observer) {
  6446. return false;
  6447. }
  6448. var index = this._observers.indexOf(observer);
  6449. if (index !== -1) {
  6450. this._observers.splice(index, 1);
  6451. return true;
  6452. }
  6453. return false;
  6454. };
  6455. /**
  6456. * Remove a callback from the Observable object
  6457. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6458. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6459. */
  6460. Observable.prototype.removeCallback = function (callback, scope) {
  6461. for (var index = 0; index < this._observers.length; index++) {
  6462. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6463. this._observers.splice(index, 1);
  6464. return true;
  6465. }
  6466. }
  6467. return false;
  6468. };
  6469. /**
  6470. * Notify all Observers by calling their respective callback with the given data
  6471. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6472. * @param eventData
  6473. * @param mask
  6474. */
  6475. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6476. if (mask === void 0) { mask = -1; }
  6477. if (!this._observers.length) {
  6478. return true;
  6479. }
  6480. var state = this._eventState;
  6481. state.mask = mask;
  6482. state.target = target;
  6483. state.currentTarget = currentTarget;
  6484. state.skipNextObservers = false;
  6485. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6486. var obs = _a[_i];
  6487. if (obs.mask & mask) {
  6488. if (obs.scope) {
  6489. obs.callback.apply(obs.scope, [eventData, state]);
  6490. }
  6491. else {
  6492. obs.callback(eventData, state);
  6493. }
  6494. }
  6495. if (state.skipNextObservers) {
  6496. return false;
  6497. }
  6498. }
  6499. return true;
  6500. };
  6501. /**
  6502. * Notify a specific observer
  6503. * @param eventData
  6504. * @param mask
  6505. */
  6506. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6507. if (mask === void 0) { mask = -1; }
  6508. var state = this._eventState;
  6509. state.mask = mask;
  6510. state.skipNextObservers = false;
  6511. observer.callback(eventData, state);
  6512. };
  6513. /**
  6514. * return true is the Observable has at least one Observer registered
  6515. */
  6516. Observable.prototype.hasObservers = function () {
  6517. return this._observers.length > 0;
  6518. };
  6519. /**
  6520. * Clear the list of observers
  6521. */
  6522. Observable.prototype.clear = function () {
  6523. this._observers = new Array();
  6524. this._onObserverAdded = null;
  6525. };
  6526. /**
  6527. * Clone the current observable
  6528. */
  6529. Observable.prototype.clone = function () {
  6530. var result = new Observable();
  6531. result._observers = this._observers.slice(0);
  6532. return result;
  6533. };
  6534. /**
  6535. * Does this observable handles observer registered with a given mask
  6536. * @param {number} trigger - the mask to be tested
  6537. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6538. **/
  6539. Observable.prototype.hasSpecificMask = function (mask) {
  6540. if (mask === void 0) { mask = -1; }
  6541. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6542. var obs = _a[_i];
  6543. if (obs.mask & mask || obs.mask === mask) {
  6544. return true;
  6545. }
  6546. }
  6547. return false;
  6548. };
  6549. return Observable;
  6550. }());
  6551. BABYLON.Observable = Observable;
  6552. })(BABYLON || (BABYLON = {}));
  6553. //# sourceMappingURL=babylon.observable.js.map
  6554. var BABYLON;
  6555. (function (BABYLON) {
  6556. var SmartArray = /** @class */ (function () {
  6557. function SmartArray(capacity) {
  6558. this.length = 0;
  6559. this.data = new Array(capacity);
  6560. this._id = SmartArray._GlobalId++;
  6561. }
  6562. SmartArray.prototype.push = function (value) {
  6563. this.data[this.length++] = value;
  6564. if (this.length > this.data.length) {
  6565. this.data.length *= 2;
  6566. }
  6567. };
  6568. SmartArray.prototype.forEach = function (func) {
  6569. for (var index = 0; index < this.length; index++) {
  6570. func(this.data[index]);
  6571. }
  6572. };
  6573. SmartArray.prototype.sort = function (compareFn) {
  6574. this.data.sort(compareFn);
  6575. };
  6576. SmartArray.prototype.reset = function () {
  6577. this.length = 0;
  6578. };
  6579. SmartArray.prototype.dispose = function () {
  6580. this.reset();
  6581. if (this.data) {
  6582. this.data.length = 0;
  6583. this.data = [];
  6584. }
  6585. };
  6586. SmartArray.prototype.concat = function (array) {
  6587. if (array.length === 0) {
  6588. return;
  6589. }
  6590. if (this.length + array.length > this.data.length) {
  6591. this.data.length = (this.length + array.length) * 2;
  6592. }
  6593. for (var index = 0; index < array.length; index++) {
  6594. this.data[this.length++] = (array.data || array)[index];
  6595. }
  6596. };
  6597. SmartArray.prototype.indexOf = function (value) {
  6598. var position = this.data.indexOf(value);
  6599. if (position >= this.length) {
  6600. return -1;
  6601. }
  6602. return position;
  6603. };
  6604. SmartArray.prototype.contains = function (value) {
  6605. return this.data.indexOf(value) !== -1;
  6606. };
  6607. // Statics
  6608. SmartArray._GlobalId = 0;
  6609. return SmartArray;
  6610. }());
  6611. BABYLON.SmartArray = SmartArray;
  6612. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6613. __extends(SmartArrayNoDuplicate, _super);
  6614. function SmartArrayNoDuplicate() {
  6615. var _this = _super !== null && _super.apply(this, arguments) || this;
  6616. _this._duplicateId = 0;
  6617. return _this;
  6618. }
  6619. SmartArrayNoDuplicate.prototype.push = function (value) {
  6620. _super.prototype.push.call(this, value);
  6621. if (!value.__smartArrayFlags) {
  6622. value.__smartArrayFlags = {};
  6623. }
  6624. value.__smartArrayFlags[this._id] = this._duplicateId;
  6625. };
  6626. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6627. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6628. return false;
  6629. }
  6630. this.push(value);
  6631. return true;
  6632. };
  6633. SmartArrayNoDuplicate.prototype.reset = function () {
  6634. _super.prototype.reset.call(this);
  6635. this._duplicateId++;
  6636. };
  6637. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6638. if (array.length === 0) {
  6639. return;
  6640. }
  6641. if (this.length + array.length > this.data.length) {
  6642. this.data.length = (this.length + array.length) * 2;
  6643. }
  6644. for (var index = 0; index < array.length; index++) {
  6645. var item = (array.data || array)[index];
  6646. this.pushNoDuplicate(item);
  6647. }
  6648. };
  6649. return SmartArrayNoDuplicate;
  6650. }(SmartArray));
  6651. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6652. })(BABYLON || (BABYLON = {}));
  6653. //# sourceMappingURL=babylon.smartArray.js.map
  6654. var BABYLON;
  6655. (function (BABYLON) {
  6656. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6657. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6658. var LoadFileError = /** @class */ (function (_super) {
  6659. __extends(LoadFileError, _super);
  6660. function LoadFileError(message, request) {
  6661. var _this = _super.call(this, message) || this;
  6662. _this.request = request;
  6663. _this.name = "LoadFileError";
  6664. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6665. return _this;
  6666. }
  6667. // Polyfill for Object.setPrototypeOf if necessary.
  6668. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6669. return LoadFileError;
  6670. }(Error));
  6671. BABYLON.LoadFileError = LoadFileError;
  6672. var RetryStrategy = /** @class */ (function () {
  6673. function RetryStrategy() {
  6674. }
  6675. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6676. if (maxRetries === void 0) { maxRetries = 3; }
  6677. if (baseInterval === void 0) { baseInterval = 500; }
  6678. return function (url, request, retryIndex) {
  6679. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6680. return -1;
  6681. }
  6682. return Math.pow(2, retryIndex) * baseInterval;
  6683. };
  6684. };
  6685. return RetryStrategy;
  6686. }());
  6687. BABYLON.RetryStrategy = RetryStrategy;
  6688. // Screenshots
  6689. var screenshotCanvas;
  6690. var cloneValue = function (source, destinationObject) {
  6691. if (!source)
  6692. return null;
  6693. if (source instanceof BABYLON.Mesh) {
  6694. return null;
  6695. }
  6696. if (source instanceof BABYLON.SubMesh) {
  6697. return source.clone(destinationObject);
  6698. }
  6699. else if (source.clone) {
  6700. return source.clone();
  6701. }
  6702. return null;
  6703. };
  6704. var Tools = /** @class */ (function () {
  6705. function Tools() {
  6706. }
  6707. /**
  6708. * Interpolates between a and b via alpha
  6709. * @param a The lower value (returned when alpha = 0)
  6710. * @param b The upper value (returned when alpha = 1)
  6711. * @param alpha The interpolation-factor
  6712. * @return The mixed value
  6713. */
  6714. Tools.Mix = function (a, b, alpha) {
  6715. return a * (1 - alpha) + b * alpha;
  6716. };
  6717. Tools.Instantiate = function (className) {
  6718. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6719. return Tools.RegisteredExternalClasses[className];
  6720. }
  6721. var arr = className.split(".");
  6722. var fn = (window || this);
  6723. for (var i = 0, len = arr.length; i < len; i++) {
  6724. fn = fn[arr[i]];
  6725. }
  6726. if (typeof fn !== "function") {
  6727. return null;
  6728. }
  6729. return fn;
  6730. };
  6731. /**
  6732. * Provides a slice function that will work even on IE
  6733. * @param data defines the array to slice
  6734. * @returns the new sliced array
  6735. */
  6736. Tools.Slice = function (data) {
  6737. if (data.slice) {
  6738. return data.slice();
  6739. }
  6740. return Array.prototype.slice.call(data);
  6741. };
  6742. Tools.SetImmediate = function (action) {
  6743. if (window.setImmediate) {
  6744. window.setImmediate(action);
  6745. }
  6746. else {
  6747. setTimeout(action, 1);
  6748. }
  6749. };
  6750. Tools.IsExponentOfTwo = function (value) {
  6751. var count = 1;
  6752. do {
  6753. count *= 2;
  6754. } while (count < value);
  6755. return count === value;
  6756. };
  6757. /**
  6758. * Find the next highest power of two.
  6759. * @param x Number to start search from.
  6760. * @return Next highest power of two.
  6761. */
  6762. Tools.CeilingPOT = function (x) {
  6763. x--;
  6764. x |= x >> 1;
  6765. x |= x >> 2;
  6766. x |= x >> 4;
  6767. x |= x >> 8;
  6768. x |= x >> 16;
  6769. x++;
  6770. return x;
  6771. };
  6772. /**
  6773. * Find the next lowest power of two.
  6774. * @param x Number to start search from.
  6775. * @return Next lowest power of two.
  6776. */
  6777. Tools.FloorPOT = function (x) {
  6778. x = x | (x >> 1);
  6779. x = x | (x >> 2);
  6780. x = x | (x >> 4);
  6781. x = x | (x >> 8);
  6782. x = x | (x >> 16);
  6783. return x - (x >> 1);
  6784. };
  6785. /**
  6786. * Find the nearest power of two.
  6787. * @param x Number to start search from.
  6788. * @return Next nearest power of two.
  6789. */
  6790. Tools.NearestPOT = function (x) {
  6791. var c = Tools.CeilingPOT(x);
  6792. var f = Tools.FloorPOT(x);
  6793. return (c - x) > (x - f) ? f : c;
  6794. };
  6795. Tools.GetExponentOfTwo = function (value, max, mode) {
  6796. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6797. var pot;
  6798. switch (mode) {
  6799. case BABYLON.Engine.SCALEMODE_FLOOR:
  6800. pot = Tools.FloorPOT(value);
  6801. break;
  6802. case BABYLON.Engine.SCALEMODE_NEAREST:
  6803. pot = Tools.NearestPOT(value);
  6804. break;
  6805. case BABYLON.Engine.SCALEMODE_CEILING:
  6806. default:
  6807. pot = Tools.CeilingPOT(value);
  6808. break;
  6809. }
  6810. return Math.min(pot, max);
  6811. };
  6812. Tools.GetFilename = function (path) {
  6813. var index = path.lastIndexOf("/");
  6814. if (index < 0)
  6815. return path;
  6816. return path.substring(index + 1);
  6817. };
  6818. Tools.GetFolderPath = function (uri) {
  6819. var index = uri.lastIndexOf("/");
  6820. if (index < 0)
  6821. return "";
  6822. return uri.substring(0, index + 1);
  6823. };
  6824. Tools.GetDOMTextContent = function (element) {
  6825. var result = "";
  6826. var child = element.firstChild;
  6827. while (child) {
  6828. if (child.nodeType === 3) {
  6829. result += child.textContent;
  6830. }
  6831. child = child.nextSibling;
  6832. }
  6833. return result;
  6834. };
  6835. Tools.ToDegrees = function (angle) {
  6836. return angle * 180 / Math.PI;
  6837. };
  6838. Tools.ToRadians = function (angle) {
  6839. return angle * Math.PI / 180;
  6840. };
  6841. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6842. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6843. var output = "";
  6844. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6845. var i = 0;
  6846. var bytes = new Uint8Array(buffer);
  6847. while (i < bytes.length) {
  6848. chr1 = bytes[i++];
  6849. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6850. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6851. enc1 = chr1 >> 2;
  6852. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6853. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6854. enc4 = chr3 & 63;
  6855. if (isNaN(chr2)) {
  6856. enc3 = enc4 = 64;
  6857. }
  6858. else if (isNaN(chr3)) {
  6859. enc4 = 64;
  6860. }
  6861. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6862. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6863. }
  6864. return "data:image/png;base64," + output;
  6865. };
  6866. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6867. if (bias === void 0) { bias = null; }
  6868. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6869. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6870. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6871. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6872. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6873. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6874. }
  6875. if (bias) {
  6876. minimum.x -= minimum.x * bias.x + bias.y;
  6877. minimum.y -= minimum.y * bias.x + bias.y;
  6878. minimum.z -= minimum.z * bias.x + bias.y;
  6879. maximum.x += maximum.x * bias.x + bias.y;
  6880. maximum.y += maximum.y * bias.x + bias.y;
  6881. maximum.z += maximum.z * bias.x + bias.y;
  6882. }
  6883. return {
  6884. minimum: minimum,
  6885. maximum: maximum
  6886. };
  6887. };
  6888. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6889. if (bias === void 0) { bias = null; }
  6890. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6891. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6892. if (!stride) {
  6893. stride = 3;
  6894. }
  6895. for (var index = start; index < start + count; index++) {
  6896. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6897. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6898. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6899. }
  6900. if (bias) {
  6901. minimum.x -= minimum.x * bias.x + bias.y;
  6902. minimum.y -= minimum.y * bias.x + bias.y;
  6903. minimum.z -= minimum.z * bias.x + bias.y;
  6904. maximum.x += maximum.x * bias.x + bias.y;
  6905. maximum.y += maximum.y * bias.x + bias.y;
  6906. maximum.z += maximum.z * bias.x + bias.y;
  6907. }
  6908. return {
  6909. minimum: minimum,
  6910. maximum: maximum
  6911. };
  6912. };
  6913. Tools.Vector2ArrayFeeder = function (array) {
  6914. return function (index) {
  6915. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6916. var length = isFloatArray ? array.length / 2 : array.length;
  6917. if (index >= length) {
  6918. return null;
  6919. }
  6920. if (isFloatArray) {
  6921. var fa = array;
  6922. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6923. }
  6924. var a = array;
  6925. return a[index];
  6926. };
  6927. };
  6928. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6929. if (bias === void 0) { bias = null; }
  6930. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6931. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6932. var i = 0;
  6933. var cur = feeder(i++);
  6934. while (cur) {
  6935. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6936. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6937. cur = feeder(i++);
  6938. }
  6939. if (bias) {
  6940. minimum.x -= minimum.x * bias.x + bias.y;
  6941. minimum.y -= minimum.y * bias.x + bias.y;
  6942. maximum.x += maximum.x * bias.x + bias.y;
  6943. maximum.y += maximum.y * bias.x + bias.y;
  6944. }
  6945. return {
  6946. minimum: minimum,
  6947. maximum: maximum
  6948. };
  6949. };
  6950. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6951. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6952. return null;
  6953. return Array.isArray(obj) ? obj : [obj];
  6954. };
  6955. // Misc.
  6956. Tools.GetPointerPrefix = function () {
  6957. var eventPrefix = "pointer";
  6958. // Check if pointer events are supported
  6959. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6960. eventPrefix = "mouse";
  6961. }
  6962. return eventPrefix;
  6963. };
  6964. /**
  6965. * @param func - the function to be called
  6966. * @param requester - the object that will request the next frame. Falls back to window.
  6967. */
  6968. Tools.QueueNewFrame = function (func, requester) {
  6969. if (!Tools.IsWindowObjectExist()) {
  6970. return setTimeout(func, 16);
  6971. }
  6972. if (!requester) {
  6973. requester = window;
  6974. }
  6975. if (requester.requestAnimationFrame) {
  6976. return requester.requestAnimationFrame(func);
  6977. }
  6978. else if (requester.msRequestAnimationFrame) {
  6979. return requester.msRequestAnimationFrame(func);
  6980. }
  6981. else if (requester.webkitRequestAnimationFrame) {
  6982. return requester.webkitRequestAnimationFrame(func);
  6983. }
  6984. else if (requester.mozRequestAnimationFrame) {
  6985. return requester.mozRequestAnimationFrame(func);
  6986. }
  6987. else if (requester.oRequestAnimationFrame) {
  6988. return requester.oRequestAnimationFrame(func);
  6989. }
  6990. else {
  6991. return window.setTimeout(func, 16);
  6992. }
  6993. };
  6994. Tools.RequestFullscreen = function (element) {
  6995. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6996. if (!requestFunction)
  6997. return;
  6998. requestFunction.call(element);
  6999. };
  7000. Tools.ExitFullscreen = function () {
  7001. if (document.exitFullscreen) {
  7002. document.exitFullscreen();
  7003. }
  7004. else if (document.mozCancelFullScreen) {
  7005. document.mozCancelFullScreen();
  7006. }
  7007. else if (document.webkitCancelFullScreen) {
  7008. document.webkitCancelFullScreen();
  7009. }
  7010. else if (document.msCancelFullScreen) {
  7011. document.msCancelFullScreen();
  7012. }
  7013. };
  7014. Tools.SetCorsBehavior = function (url, element) {
  7015. if (url && url.indexOf("data:") === 0) {
  7016. return;
  7017. }
  7018. if (Tools.CorsBehavior) {
  7019. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7020. element.crossOrigin = Tools.CorsBehavior;
  7021. }
  7022. else {
  7023. var result = Tools.CorsBehavior(url);
  7024. if (result) {
  7025. element.crossOrigin = result;
  7026. }
  7027. }
  7028. }
  7029. };
  7030. // External files
  7031. Tools.CleanUrl = function (url) {
  7032. url = url.replace(/#/mg, "%23");
  7033. return url;
  7034. };
  7035. Tools.LoadImage = function (url, onLoad, onError, database) {
  7036. if (url instanceof ArrayBuffer) {
  7037. url = Tools.EncodeArrayBufferTobase64(url);
  7038. }
  7039. url = Tools.CleanUrl(url);
  7040. url = Tools.PreprocessUrl(url);
  7041. var img = new Image();
  7042. Tools.SetCorsBehavior(url, img);
  7043. img.onload = function () {
  7044. onLoad(img);
  7045. };
  7046. img.onerror = function (err) {
  7047. Tools.Error("Error while trying to load image: " + url);
  7048. if (onError) {
  7049. onError("Error while trying to load image: " + url, err);
  7050. }
  7051. };
  7052. var noIndexedDB = function () {
  7053. img.src = url;
  7054. };
  7055. var loadFromIndexedDB = function () {
  7056. if (database) {
  7057. database.loadImageFromDB(url, img);
  7058. }
  7059. };
  7060. //ANY database to do!
  7061. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7062. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7063. }
  7064. else {
  7065. if (url.indexOf("file:") !== -1) {
  7066. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7067. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7068. try {
  7069. var blobURL;
  7070. try {
  7071. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7072. }
  7073. catch (ex) {
  7074. // Chrome doesn't support oneTimeOnly parameter
  7075. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7076. }
  7077. img.src = blobURL;
  7078. }
  7079. catch (e) {
  7080. img.src = "";
  7081. }
  7082. return img;
  7083. }
  7084. }
  7085. noIndexedDB();
  7086. }
  7087. return img;
  7088. };
  7089. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7090. url = Tools.CleanUrl(url);
  7091. url = Tools.PreprocessUrl(url);
  7092. // If file and file input are set
  7093. if (url.indexOf("file:") !== -1) {
  7094. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7095. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7096. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7097. }
  7098. }
  7099. var loadUrl = Tools.BaseUrl + url;
  7100. var aborted = false;
  7101. var fileRequest = {
  7102. onCompleteObservable: new BABYLON.Observable(),
  7103. abort: function () { return aborted = true; },
  7104. };
  7105. var requestFile = function () {
  7106. var request = new XMLHttpRequest();
  7107. var retryHandle = null;
  7108. fileRequest.abort = function () {
  7109. aborted = true;
  7110. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7111. request.abort();
  7112. }
  7113. if (retryHandle !== null) {
  7114. clearTimeout(retryHandle);
  7115. retryHandle = null;
  7116. }
  7117. };
  7118. var retryLoop = function (retryIndex) {
  7119. request.open('GET', loadUrl, true);
  7120. if (useArrayBuffer) {
  7121. request.responseType = "arraybuffer";
  7122. }
  7123. if (onProgress) {
  7124. request.addEventListener("progress", onProgress);
  7125. }
  7126. var onLoadEnd = function () {
  7127. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7128. };
  7129. request.addEventListener("loadend", onLoadEnd);
  7130. var onReadyStateChange = function () {
  7131. if (aborted) {
  7132. return;
  7133. }
  7134. // In case of undefined state in some browsers.
  7135. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7136. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7137. request.removeEventListener("readystatechange", onReadyStateChange);
  7138. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7139. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7140. return;
  7141. }
  7142. var retryStrategy = Tools.DefaultRetryStrategy;
  7143. if (retryStrategy) {
  7144. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7145. if (waitTime !== -1) {
  7146. // Prevent the request from completing for retry.
  7147. request.removeEventListener("loadend", onLoadEnd);
  7148. request = new XMLHttpRequest();
  7149. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7150. return;
  7151. }
  7152. }
  7153. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7154. if (onError) {
  7155. onError(request, e);
  7156. }
  7157. else {
  7158. throw e;
  7159. }
  7160. }
  7161. };
  7162. request.addEventListener("readystatechange", onReadyStateChange);
  7163. request.send();
  7164. };
  7165. retryLoop(0);
  7166. };
  7167. // Caching all files
  7168. if (database && database.enableSceneOffline) {
  7169. var noIndexedDB_1 = function () {
  7170. if (!aborted) {
  7171. requestFile();
  7172. }
  7173. };
  7174. var loadFromIndexedDB = function () {
  7175. // TODO: database needs to support aborting and should return a IFileRequest
  7176. if (aborted) {
  7177. return;
  7178. }
  7179. if (database) {
  7180. database.loadFileFromDB(url, function (data) {
  7181. if (!aborted) {
  7182. onSuccess(data);
  7183. }
  7184. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7185. }, onProgress ? function (event) {
  7186. if (!aborted) {
  7187. onProgress(event);
  7188. }
  7189. } : undefined, noIndexedDB_1, useArrayBuffer);
  7190. }
  7191. };
  7192. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7193. }
  7194. else {
  7195. requestFile();
  7196. }
  7197. return fileRequest;
  7198. };
  7199. /**
  7200. * Load a script (identified by an url). When the url returns, the
  7201. * content of this file is added into a new script element, attached to the DOM (body element)
  7202. */
  7203. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7204. var head = document.getElementsByTagName('head')[0];
  7205. var script = document.createElement('script');
  7206. script.type = 'text/javascript';
  7207. script.src = scriptUrl;
  7208. script.onload = function () {
  7209. if (onSuccess) {
  7210. onSuccess();
  7211. }
  7212. };
  7213. script.onerror = function (e) {
  7214. if (onError) {
  7215. onError("Unable to load script", e);
  7216. }
  7217. };
  7218. head.appendChild(script);
  7219. };
  7220. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7221. var reader = new FileReader();
  7222. var request = {
  7223. onCompleteObservable: new BABYLON.Observable(),
  7224. abort: function () { return reader.abort(); },
  7225. };
  7226. reader.onloadend = function (e) {
  7227. request.onCompleteObservable.notifyObservers(request);
  7228. };
  7229. reader.onload = function (e) {
  7230. //target doesn't have result from ts 1.3
  7231. callback(e.target['result']);
  7232. };
  7233. reader.onprogress = progressCallback;
  7234. reader.readAsDataURL(fileToLoad);
  7235. return request;
  7236. };
  7237. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7238. var reader = new FileReader();
  7239. var request = {
  7240. onCompleteObservable: new BABYLON.Observable(),
  7241. abort: function () { return reader.abort(); },
  7242. };
  7243. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7244. reader.onerror = function (e) {
  7245. Tools.Log("Error while reading file: " + fileToLoad.name);
  7246. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7247. };
  7248. reader.onload = function (e) {
  7249. //target doesn't have result from ts 1.3
  7250. callback(e.target['result']);
  7251. };
  7252. if (progressCallBack) {
  7253. reader.onprogress = progressCallBack;
  7254. }
  7255. if (!useArrayBuffer) {
  7256. // Asynchronous read
  7257. reader.readAsText(fileToLoad);
  7258. }
  7259. else {
  7260. reader.readAsArrayBuffer(fileToLoad);
  7261. }
  7262. return request;
  7263. };
  7264. //returns a downloadable url to a file content.
  7265. Tools.FileAsURL = function (content) {
  7266. var fileBlob = new Blob([content]);
  7267. var url = window.URL || window.webkitURL;
  7268. var link = url.createObjectURL(fileBlob);
  7269. return link;
  7270. };
  7271. // Misc.
  7272. Tools.Format = function (value, decimals) {
  7273. if (decimals === void 0) { decimals = 2; }
  7274. return value.toFixed(decimals);
  7275. };
  7276. Tools.CheckExtends = function (v, min, max) {
  7277. if (v.x < min.x)
  7278. min.x = v.x;
  7279. if (v.y < min.y)
  7280. min.y = v.y;
  7281. if (v.z < min.z)
  7282. min.z = v.z;
  7283. if (v.x > max.x)
  7284. max.x = v.x;
  7285. if (v.y > max.y)
  7286. max.y = v.y;
  7287. if (v.z > max.z)
  7288. max.z = v.z;
  7289. };
  7290. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7291. for (var prop in source) {
  7292. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7293. continue;
  7294. }
  7295. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7296. continue;
  7297. }
  7298. var sourceValue = source[prop];
  7299. var typeOfSourceValue = typeof sourceValue;
  7300. if (typeOfSourceValue === "function") {
  7301. continue;
  7302. }
  7303. if (typeOfSourceValue === "object") {
  7304. if (sourceValue instanceof Array) {
  7305. destination[prop] = [];
  7306. if (sourceValue.length > 0) {
  7307. if (typeof sourceValue[0] == "object") {
  7308. for (var index = 0; index < sourceValue.length; index++) {
  7309. var clonedValue = cloneValue(sourceValue[index], destination);
  7310. if (destination[prop].indexOf(clonedValue) === -1) {
  7311. destination[prop].push(clonedValue);
  7312. }
  7313. }
  7314. }
  7315. else {
  7316. destination[prop] = sourceValue.slice(0);
  7317. }
  7318. }
  7319. }
  7320. else {
  7321. destination[prop] = cloneValue(sourceValue, destination);
  7322. }
  7323. }
  7324. else {
  7325. destination[prop] = sourceValue;
  7326. }
  7327. }
  7328. };
  7329. Tools.IsEmpty = function (obj) {
  7330. for (var i in obj) {
  7331. if (obj.hasOwnProperty(i)) {
  7332. return false;
  7333. }
  7334. }
  7335. return true;
  7336. };
  7337. Tools.RegisterTopRootEvents = function (events) {
  7338. for (var index = 0; index < events.length; index++) {
  7339. var event = events[index];
  7340. window.addEventListener(event.name, event.handler, false);
  7341. try {
  7342. if (window.parent) {
  7343. window.parent.addEventListener(event.name, event.handler, false);
  7344. }
  7345. }
  7346. catch (e) {
  7347. // Silently fails...
  7348. }
  7349. }
  7350. };
  7351. Tools.UnregisterTopRootEvents = function (events) {
  7352. for (var index = 0; index < events.length; index++) {
  7353. var event = events[index];
  7354. window.removeEventListener(event.name, event.handler);
  7355. try {
  7356. if (window.parent) {
  7357. window.parent.removeEventListener(event.name, event.handler);
  7358. }
  7359. }
  7360. catch (e) {
  7361. // Silently fails...
  7362. }
  7363. }
  7364. };
  7365. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7366. if (mimeType === void 0) { mimeType = "image/png"; }
  7367. // Read the contents of the framebuffer
  7368. var numberOfChannelsByLine = width * 4;
  7369. var halfHeight = height / 2;
  7370. //Reading datas from WebGL
  7371. var data = engine.readPixels(0, 0, width, height);
  7372. //To flip image on Y axis.
  7373. for (var i = 0; i < halfHeight; i++) {
  7374. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7375. var currentCell = j + i * numberOfChannelsByLine;
  7376. var targetLine = height - i - 1;
  7377. var targetCell = j + targetLine * numberOfChannelsByLine;
  7378. var temp = data[currentCell];
  7379. data[currentCell] = data[targetCell];
  7380. data[targetCell] = temp;
  7381. }
  7382. }
  7383. // Create a 2D canvas to store the result
  7384. if (!screenshotCanvas) {
  7385. screenshotCanvas = document.createElement('canvas');
  7386. }
  7387. screenshotCanvas.width = width;
  7388. screenshotCanvas.height = height;
  7389. var context = screenshotCanvas.getContext('2d');
  7390. if (context) {
  7391. // Copy the pixels to a 2D canvas
  7392. var imageData = context.createImageData(width, height);
  7393. var castData = (imageData.data);
  7394. castData.set(data);
  7395. context.putImageData(imageData, 0, 0);
  7396. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7397. }
  7398. };
  7399. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7400. if (mimeType === void 0) { mimeType = "image/png"; }
  7401. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7402. if (successCallback) {
  7403. successCallback(base64Image);
  7404. }
  7405. else {
  7406. // We need HTMLCanvasElement.toBlob for HD screenshots
  7407. if (!screenshotCanvas.toBlob) {
  7408. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7409. screenshotCanvas.toBlob = function (callback, type, quality) {
  7410. var _this = this;
  7411. setTimeout(function () {
  7412. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7413. for (var i = 0; i < len; i++) {
  7414. arr[i] = binStr.charCodeAt(i);
  7415. }
  7416. callback(new Blob([arr], { type: type || 'image/png' }));
  7417. });
  7418. };
  7419. }
  7420. screenshotCanvas.toBlob(function (blob) {
  7421. var url = URL.createObjectURL(blob);
  7422. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7423. if (("download" in document.createElement("a"))) {
  7424. var a = window.document.createElement("a");
  7425. a.href = url;
  7426. if (fileName) {
  7427. a.setAttribute("download", fileName);
  7428. }
  7429. else {
  7430. var date = new Date();
  7431. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7432. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7433. }
  7434. window.document.body.appendChild(a);
  7435. a.addEventListener("click", function () {
  7436. if (a.parentElement) {
  7437. a.parentElement.removeChild(a);
  7438. }
  7439. });
  7440. a.click();
  7441. }
  7442. else {
  7443. var newWindow = window.open("");
  7444. if (!newWindow)
  7445. return;
  7446. var img = newWindow.document.createElement("img");
  7447. img.onload = function () {
  7448. // no longer need to read the blob so it's revoked
  7449. URL.revokeObjectURL(url);
  7450. };
  7451. img.src = url;
  7452. newWindow.document.body.appendChild(img);
  7453. }
  7454. });
  7455. }
  7456. };
  7457. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7458. if (mimeType === void 0) { mimeType = "image/png"; }
  7459. var width;
  7460. var height;
  7461. // If a precision value is specified
  7462. if (size.precision) {
  7463. width = Math.round(engine.getRenderWidth() * size.precision);
  7464. height = Math.round(width / engine.getAspectRatio(camera));
  7465. }
  7466. else if (size.width && size.height) {
  7467. width = size.width;
  7468. height = size.height;
  7469. }
  7470. else if (size.width && !size.height) {
  7471. width = size.width;
  7472. height = Math.round(width / engine.getAspectRatio(camera));
  7473. }
  7474. else if (size.height && !size.width) {
  7475. height = size.height;
  7476. width = Math.round(height * engine.getAspectRatio(camera));
  7477. }
  7478. else if (!isNaN(size)) {
  7479. height = size;
  7480. width = size;
  7481. }
  7482. else {
  7483. Tools.Error("Invalid 'size' parameter !");
  7484. return;
  7485. }
  7486. if (!screenshotCanvas) {
  7487. screenshotCanvas = document.createElement('canvas');
  7488. }
  7489. screenshotCanvas.width = width;
  7490. screenshotCanvas.height = height;
  7491. var renderContext = screenshotCanvas.getContext("2d");
  7492. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7493. var newWidth = width;
  7494. var newHeight = newWidth / ratio;
  7495. if (newHeight > height) {
  7496. newHeight = height;
  7497. newWidth = newHeight * ratio;
  7498. }
  7499. var offsetX = Math.max(0, width - newWidth) / 2;
  7500. var offsetY = Math.max(0, height - newHeight) / 2;
  7501. var renderingCanvas = engine.getRenderingCanvas();
  7502. if (renderContext && renderingCanvas) {
  7503. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7504. }
  7505. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7506. };
  7507. /**
  7508. * Generates an image screenshot from the specified camera.
  7509. *
  7510. * @param engine The engine to use for rendering
  7511. * @param camera The camera to use for rendering
  7512. * @param size This parameter can be set to a single number or to an object with the
  7513. * following (optional) properties: precision, width, height. If a single number is passed,
  7514. * it will be used for both width and height. If an object is passed, the screenshot size
  7515. * will be derived from the parameters. The precision property is a multiplier allowing
  7516. * rendering at a higher or lower resolution.
  7517. * @param successCallback The callback receives a single parameter which contains the
  7518. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7519. * src parameter of an <img> to display it.
  7520. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7521. * Check your browser for supported MIME types.
  7522. * @param samples Texture samples (default: 1)
  7523. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7524. * @param fileName A name for for the downloaded file.
  7525. * @constructor
  7526. */
  7527. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7528. if (mimeType === void 0) { mimeType = "image/png"; }
  7529. if (samples === void 0) { samples = 1; }
  7530. if (antialiasing === void 0) { antialiasing = false; }
  7531. var width;
  7532. var height;
  7533. //If a precision value is specified
  7534. if (size.precision) {
  7535. width = Math.round(engine.getRenderWidth() * size.precision);
  7536. height = Math.round(width / engine.getAspectRatio(camera));
  7537. size = { width: width, height: height };
  7538. }
  7539. else if (size.width && size.height) {
  7540. width = size.width;
  7541. height = size.height;
  7542. }
  7543. else if (size.width && !size.height) {
  7544. width = size.width;
  7545. height = Math.round(width / engine.getAspectRatio(camera));
  7546. size = { width: width, height: height };
  7547. }
  7548. else if (size.height && !size.width) {
  7549. height = size.height;
  7550. width = Math.round(height * engine.getAspectRatio(camera));
  7551. size = { width: width, height: height };
  7552. }
  7553. else if (!isNaN(size)) {
  7554. height = size;
  7555. width = size;
  7556. }
  7557. else {
  7558. Tools.Error("Invalid 'size' parameter !");
  7559. return;
  7560. }
  7561. var scene = camera.getScene();
  7562. var previousCamera = null;
  7563. if (scene.activeCamera !== camera) {
  7564. previousCamera = scene.activeCamera;
  7565. scene.activeCamera = camera;
  7566. }
  7567. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7568. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7569. texture.renderList = null;
  7570. texture.samples = samples;
  7571. if (antialiasing) {
  7572. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7573. }
  7574. texture.onAfterRenderObservable.add(function () {
  7575. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7576. });
  7577. scene.incrementRenderId();
  7578. scene.resetCachedMaterial();
  7579. texture.render(true);
  7580. texture.dispose();
  7581. if (previousCamera) {
  7582. scene.activeCamera = previousCamera;
  7583. }
  7584. camera.getProjectionMatrix(true); // Force cache refresh;
  7585. };
  7586. // XHR response validator for local file scenario
  7587. Tools.ValidateXHRData = function (xhr, dataType) {
  7588. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7589. if (dataType === void 0) { dataType = 7; }
  7590. try {
  7591. if (dataType & 1) {
  7592. if (xhr.responseText && xhr.responseText.length > 0) {
  7593. return true;
  7594. }
  7595. else if (dataType === 1) {
  7596. return false;
  7597. }
  7598. }
  7599. if (dataType & 2) {
  7600. // Check header width and height since there is no "TGA" magic number
  7601. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7602. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7603. return true;
  7604. }
  7605. else if (dataType === 2) {
  7606. return false;
  7607. }
  7608. }
  7609. if (dataType & 4) {
  7610. // Check for the "DDS" magic number
  7611. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7612. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7613. return true;
  7614. }
  7615. else {
  7616. return false;
  7617. }
  7618. }
  7619. }
  7620. catch (e) {
  7621. // Global protection
  7622. }
  7623. return false;
  7624. };
  7625. /**
  7626. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7627. * Be aware Math.random() could cause collisions, but:
  7628. * "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"
  7629. */
  7630. Tools.RandomId = function () {
  7631. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7632. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7633. return v.toString(16);
  7634. });
  7635. };
  7636. Object.defineProperty(Tools, "NoneLogLevel", {
  7637. get: function () {
  7638. return Tools._NoneLogLevel;
  7639. },
  7640. enumerable: true,
  7641. configurable: true
  7642. });
  7643. Object.defineProperty(Tools, "MessageLogLevel", {
  7644. get: function () {
  7645. return Tools._MessageLogLevel;
  7646. },
  7647. enumerable: true,
  7648. configurable: true
  7649. });
  7650. Object.defineProperty(Tools, "WarningLogLevel", {
  7651. get: function () {
  7652. return Tools._WarningLogLevel;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. Object.defineProperty(Tools, "ErrorLogLevel", {
  7658. get: function () {
  7659. return Tools._ErrorLogLevel;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(Tools, "AllLogLevel", {
  7665. get: function () {
  7666. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7667. },
  7668. enumerable: true,
  7669. configurable: true
  7670. });
  7671. Tools._AddLogEntry = function (entry) {
  7672. Tools._LogCache = entry + Tools._LogCache;
  7673. if (Tools.OnNewCacheEntry) {
  7674. Tools.OnNewCacheEntry(entry);
  7675. }
  7676. };
  7677. Tools._FormatMessage = function (message) {
  7678. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7679. var date = new Date();
  7680. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7681. };
  7682. Tools._LogDisabled = function (message) {
  7683. // nothing to do
  7684. };
  7685. Tools._LogEnabled = function (message) {
  7686. var formattedMessage = Tools._FormatMessage(message);
  7687. console.log("BJS - " + formattedMessage);
  7688. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7689. Tools._AddLogEntry(entry);
  7690. };
  7691. Tools._WarnDisabled = function (message) {
  7692. // nothing to do
  7693. };
  7694. Tools._WarnEnabled = function (message) {
  7695. var formattedMessage = Tools._FormatMessage(message);
  7696. console.warn("BJS - " + formattedMessage);
  7697. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7698. Tools._AddLogEntry(entry);
  7699. };
  7700. Tools._ErrorDisabled = function (message) {
  7701. // nothing to do
  7702. };
  7703. Tools._ErrorEnabled = function (message) {
  7704. Tools.errorsCount++;
  7705. var formattedMessage = Tools._FormatMessage(message);
  7706. console.error("BJS - " + formattedMessage);
  7707. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7708. Tools._AddLogEntry(entry);
  7709. };
  7710. Object.defineProperty(Tools, "LogCache", {
  7711. get: function () {
  7712. return Tools._LogCache;
  7713. },
  7714. enumerable: true,
  7715. configurable: true
  7716. });
  7717. Tools.ClearLogCache = function () {
  7718. Tools._LogCache = "";
  7719. Tools.errorsCount = 0;
  7720. };
  7721. Object.defineProperty(Tools, "LogLevels", {
  7722. set: function (level) {
  7723. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7724. Tools.Log = Tools._LogEnabled;
  7725. }
  7726. else {
  7727. Tools.Log = Tools._LogDisabled;
  7728. }
  7729. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7730. Tools.Warn = Tools._WarnEnabled;
  7731. }
  7732. else {
  7733. Tools.Warn = Tools._WarnDisabled;
  7734. }
  7735. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7736. Tools.Error = Tools._ErrorEnabled;
  7737. }
  7738. else {
  7739. Tools.Error = Tools._ErrorDisabled;
  7740. }
  7741. },
  7742. enumerable: true,
  7743. configurable: true
  7744. });
  7745. Tools.IsWindowObjectExist = function () {
  7746. return (typeof window) !== "undefined";
  7747. };
  7748. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7749. get: function () {
  7750. return Tools._PerformanceNoneLogLevel;
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7756. get: function () {
  7757. return Tools._PerformanceUserMarkLogLevel;
  7758. },
  7759. enumerable: true,
  7760. configurable: true
  7761. });
  7762. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7763. get: function () {
  7764. return Tools._PerformanceConsoleLogLevel;
  7765. },
  7766. enumerable: true,
  7767. configurable: true
  7768. });
  7769. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7770. set: function (level) {
  7771. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7772. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7773. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7774. return;
  7775. }
  7776. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7777. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7778. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7779. return;
  7780. }
  7781. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7782. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7783. },
  7784. enumerable: true,
  7785. configurable: true
  7786. });
  7787. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7788. };
  7789. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7790. };
  7791. Tools._StartUserMark = function (counterName, condition) {
  7792. if (condition === void 0) { condition = true; }
  7793. if (!Tools._performance) {
  7794. if (!Tools.IsWindowObjectExist()) {
  7795. return;
  7796. }
  7797. Tools._performance = window.performance;
  7798. }
  7799. if (!condition || !Tools._performance.mark) {
  7800. return;
  7801. }
  7802. Tools._performance.mark(counterName + "-Begin");
  7803. };
  7804. Tools._EndUserMark = function (counterName, condition) {
  7805. if (condition === void 0) { condition = true; }
  7806. if (!condition || !Tools._performance.mark) {
  7807. return;
  7808. }
  7809. Tools._performance.mark(counterName + "-End");
  7810. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7811. };
  7812. Tools._StartPerformanceConsole = function (counterName, condition) {
  7813. if (condition === void 0) { condition = true; }
  7814. if (!condition) {
  7815. return;
  7816. }
  7817. Tools._StartUserMark(counterName, condition);
  7818. if (console.time) {
  7819. console.time(counterName);
  7820. }
  7821. };
  7822. Tools._EndPerformanceConsole = function (counterName, condition) {
  7823. if (condition === void 0) { condition = true; }
  7824. if (!condition) {
  7825. return;
  7826. }
  7827. Tools._EndUserMark(counterName, condition);
  7828. if (console.time) {
  7829. console.timeEnd(counterName);
  7830. }
  7831. };
  7832. Object.defineProperty(Tools, "Now", {
  7833. get: function () {
  7834. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7835. return window.performance.now();
  7836. }
  7837. return new Date().getTime();
  7838. },
  7839. enumerable: true,
  7840. configurable: true
  7841. });
  7842. /**
  7843. * This method will return the name of the class used to create the instance of the given object.
  7844. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7845. * @param object the object to get the class name from
  7846. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7847. */
  7848. Tools.GetClassName = function (object, isType) {
  7849. if (isType === void 0) { isType = false; }
  7850. var name = null;
  7851. if (!isType && object.getClassName) {
  7852. name = object.getClassName();
  7853. }
  7854. else {
  7855. if (object instanceof Object) {
  7856. var classObj = isType ? object : Object.getPrototypeOf(object);
  7857. name = classObj.constructor["__bjsclassName__"];
  7858. }
  7859. if (!name) {
  7860. name = typeof object;
  7861. }
  7862. }
  7863. return name;
  7864. };
  7865. Tools.First = function (array, predicate) {
  7866. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7867. var el = array_1[_i];
  7868. if (predicate(el)) {
  7869. return el;
  7870. }
  7871. }
  7872. return null;
  7873. };
  7874. /**
  7875. * This method will return the name of the full name of the class, including its owning module (if any).
  7876. * 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).
  7877. * @param object the object to get the class name from
  7878. * @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.
  7879. */
  7880. Tools.getFullClassName = function (object, isType) {
  7881. if (isType === void 0) { isType = false; }
  7882. var className = null;
  7883. var moduleName = null;
  7884. if (!isType && object.getClassName) {
  7885. className = object.getClassName();
  7886. }
  7887. else {
  7888. if (object instanceof Object) {
  7889. var classObj = isType ? object : Object.getPrototypeOf(object);
  7890. className = classObj.constructor["__bjsclassName__"];
  7891. moduleName = classObj.constructor["__bjsmoduleName__"];
  7892. }
  7893. if (!className) {
  7894. className = typeof object;
  7895. }
  7896. }
  7897. if (!className) {
  7898. return null;
  7899. }
  7900. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7901. };
  7902. /**
  7903. * 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.
  7904. * @param array
  7905. */
  7906. Tools.arrayOrStringFeeder = function (array) {
  7907. return function (index) {
  7908. if (index >= array.length) {
  7909. return null;
  7910. }
  7911. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7912. if (val && val.getHashCode) {
  7913. val = val.getHashCode();
  7914. }
  7915. if (typeof val === "string") {
  7916. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7917. }
  7918. return val;
  7919. };
  7920. };
  7921. /**
  7922. * Compute the hashCode of a stream of number
  7923. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7924. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7925. * @return the hash code computed
  7926. */
  7927. Tools.hashCodeFromStream = function (feeder) {
  7928. // Based from here: http://stackoverflow.com/a/7616484/802124
  7929. var hash = 0;
  7930. var index = 0;
  7931. var chr = feeder(index++);
  7932. while (chr != null) {
  7933. hash = ((hash << 5) - hash) + chr;
  7934. hash |= 0; // Convert to 32bit integer
  7935. chr = feeder(index++);
  7936. }
  7937. return hash;
  7938. };
  7939. Tools.BaseUrl = "";
  7940. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7941. /**
  7942. * Default behaviour for cors in the application.
  7943. * It can be a string if the expected behavior is identical in the entire app.
  7944. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7945. */
  7946. Tools.CorsBehavior = "anonymous";
  7947. Tools.UseFallbackTexture = true;
  7948. /**
  7949. * Use this object to register external classes like custom textures or material
  7950. * to allow the laoders to instantiate them
  7951. */
  7952. Tools.RegisteredExternalClasses = {};
  7953. // Used in case of a texture loading problem
  7954. 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";
  7955. Tools.PreprocessUrl = function (url) {
  7956. return url;
  7957. };
  7958. // Logs
  7959. Tools._NoneLogLevel = 0;
  7960. Tools._MessageLogLevel = 1;
  7961. Tools._WarningLogLevel = 2;
  7962. Tools._ErrorLogLevel = 4;
  7963. Tools._LogCache = "";
  7964. Tools.errorsCount = 0;
  7965. Tools.Log = Tools._LogEnabled;
  7966. Tools.Warn = Tools._WarnEnabled;
  7967. Tools.Error = Tools._ErrorEnabled;
  7968. // Performances
  7969. Tools._PerformanceNoneLogLevel = 0;
  7970. Tools._PerformanceUserMarkLogLevel = 1;
  7971. Tools._PerformanceConsoleLogLevel = 2;
  7972. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7973. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7974. return Tools;
  7975. }());
  7976. BABYLON.Tools = Tools;
  7977. /**
  7978. * This class is used to track a performance counter which is number based.
  7979. * The user has access to many properties which give statistics of different nature
  7980. *
  7981. * The implementer can track two kinds of Performance Counter: time and count
  7982. * 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.
  7983. * 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.
  7984. */
  7985. var PerfCounter = /** @class */ (function () {
  7986. function PerfCounter() {
  7987. this._startMonitoringTime = 0;
  7988. this._min = 0;
  7989. this._max = 0;
  7990. this._average = 0;
  7991. this._lastSecAverage = 0;
  7992. this._current = 0;
  7993. this._totalValueCount = 0;
  7994. this._totalAccumulated = 0;
  7995. this._lastSecAccumulated = 0;
  7996. this._lastSecTime = 0;
  7997. this._lastSecValueCount = 0;
  7998. }
  7999. Object.defineProperty(PerfCounter.prototype, "min", {
  8000. /**
  8001. * Returns the smallest value ever
  8002. */
  8003. get: function () {
  8004. return this._min;
  8005. },
  8006. enumerable: true,
  8007. configurable: true
  8008. });
  8009. Object.defineProperty(PerfCounter.prototype, "max", {
  8010. /**
  8011. * Returns the biggest value ever
  8012. */
  8013. get: function () {
  8014. return this._max;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(PerfCounter.prototype, "average", {
  8020. /**
  8021. * Returns the average value since the performance counter is running
  8022. */
  8023. get: function () {
  8024. return this._average;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8030. /**
  8031. * Returns the average value of the last second the counter was monitored
  8032. */
  8033. get: function () {
  8034. return this._lastSecAverage;
  8035. },
  8036. enumerable: true,
  8037. configurable: true
  8038. });
  8039. Object.defineProperty(PerfCounter.prototype, "current", {
  8040. /**
  8041. * Returns the current value
  8042. */
  8043. get: function () {
  8044. return this._current;
  8045. },
  8046. enumerable: true,
  8047. configurable: true
  8048. });
  8049. Object.defineProperty(PerfCounter.prototype, "total", {
  8050. get: function () {
  8051. return this._totalAccumulated;
  8052. },
  8053. enumerable: true,
  8054. configurable: true
  8055. });
  8056. Object.defineProperty(PerfCounter.prototype, "count", {
  8057. get: function () {
  8058. return this._totalValueCount;
  8059. },
  8060. enumerable: true,
  8061. configurable: true
  8062. });
  8063. /**
  8064. * Call this method to start monitoring a new frame.
  8065. * 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.
  8066. */
  8067. PerfCounter.prototype.fetchNewFrame = function () {
  8068. this._totalValueCount++;
  8069. this._current = 0;
  8070. this._lastSecValueCount++;
  8071. };
  8072. /**
  8073. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8074. * @param newCount the count value to add to the monitored count
  8075. * @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.
  8076. */
  8077. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8078. if (!PerfCounter.Enabled) {
  8079. return;
  8080. }
  8081. this._current += newCount;
  8082. if (fetchResult) {
  8083. this._fetchResult();
  8084. }
  8085. };
  8086. /**
  8087. * Start monitoring this performance counter
  8088. */
  8089. PerfCounter.prototype.beginMonitoring = function () {
  8090. if (!PerfCounter.Enabled) {
  8091. return;
  8092. }
  8093. this._startMonitoringTime = Tools.Now;
  8094. };
  8095. /**
  8096. * Compute the time lapsed since the previous beginMonitoring() call.
  8097. * @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
  8098. */
  8099. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8100. if (newFrame === void 0) { newFrame = true; }
  8101. if (!PerfCounter.Enabled) {
  8102. return;
  8103. }
  8104. if (newFrame) {
  8105. this.fetchNewFrame();
  8106. }
  8107. var currentTime = Tools.Now;
  8108. this._current = currentTime - this._startMonitoringTime;
  8109. if (newFrame) {
  8110. this._fetchResult();
  8111. }
  8112. };
  8113. PerfCounter.prototype._fetchResult = function () {
  8114. this._totalAccumulated += this._current;
  8115. this._lastSecAccumulated += this._current;
  8116. // Min/Max update
  8117. this._min = Math.min(this._min, this._current);
  8118. this._max = Math.max(this._max, this._current);
  8119. this._average = this._totalAccumulated / this._totalValueCount;
  8120. // Reset last sec?
  8121. var now = Tools.Now;
  8122. if ((now - this._lastSecTime) > 1000) {
  8123. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8124. this._lastSecTime = now;
  8125. this._lastSecAccumulated = 0;
  8126. this._lastSecValueCount = 0;
  8127. }
  8128. };
  8129. PerfCounter.Enabled = true;
  8130. return PerfCounter;
  8131. }());
  8132. BABYLON.PerfCounter = PerfCounter;
  8133. /**
  8134. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8135. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8136. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8137. * @param name The name of the class, case should be preserved
  8138. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8139. */
  8140. function className(name, module) {
  8141. return function (target) {
  8142. target["__bjsclassName__"] = name;
  8143. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8144. };
  8145. }
  8146. BABYLON.className = className;
  8147. /**
  8148. * An implementation of a loop for asynchronous functions.
  8149. */
  8150. var AsyncLoop = /** @class */ (function () {
  8151. /**
  8152. * Constroctor.
  8153. * @param iterations the number of iterations.
  8154. * @param _fn the function to run each iteration
  8155. * @param _successCallback the callback that will be called upon succesful execution
  8156. * @param offset starting offset.
  8157. */
  8158. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8159. if (offset === void 0) { offset = 0; }
  8160. this.iterations = iterations;
  8161. this._fn = _fn;
  8162. this._successCallback = _successCallback;
  8163. this.index = offset - 1;
  8164. this._done = false;
  8165. }
  8166. /**
  8167. * Execute the next iteration. Must be called after the last iteration was finished.
  8168. */
  8169. AsyncLoop.prototype.executeNext = function () {
  8170. if (!this._done) {
  8171. if (this.index + 1 < this.iterations) {
  8172. ++this.index;
  8173. this._fn(this);
  8174. }
  8175. else {
  8176. this.breakLoop();
  8177. }
  8178. }
  8179. };
  8180. /**
  8181. * Break the loop and run the success callback.
  8182. */
  8183. AsyncLoop.prototype.breakLoop = function () {
  8184. this._done = true;
  8185. this._successCallback();
  8186. };
  8187. /**
  8188. * Helper function
  8189. */
  8190. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8191. if (offset === void 0) { offset = 0; }
  8192. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8193. loop.executeNext();
  8194. return loop;
  8195. };
  8196. /**
  8197. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8198. * @param iterations total number of iterations
  8199. * @param syncedIterations number of synchronous iterations in each async iteration.
  8200. * @param fn the function to call each iteration.
  8201. * @param callback a success call back that will be called when iterating stops.
  8202. * @param breakFunction a break condition (optional)
  8203. * @param timeout timeout settings for the setTimeout function. default - 0.
  8204. * @constructor
  8205. */
  8206. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8207. if (timeout === void 0) { timeout = 0; }
  8208. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8209. if (breakFunction && breakFunction())
  8210. loop.breakLoop();
  8211. else {
  8212. setTimeout(function () {
  8213. for (var i = 0; i < syncedIterations; ++i) {
  8214. var iteration = (loop.index * syncedIterations) + i;
  8215. if (iteration >= iterations)
  8216. break;
  8217. fn(iteration);
  8218. if (breakFunction && breakFunction()) {
  8219. loop.breakLoop();
  8220. break;
  8221. }
  8222. }
  8223. loop.executeNext();
  8224. }, timeout);
  8225. }
  8226. }, callback);
  8227. };
  8228. return AsyncLoop;
  8229. }());
  8230. BABYLON.AsyncLoop = AsyncLoop;
  8231. })(BABYLON || (BABYLON = {}));
  8232. //# sourceMappingURL=babylon.tools.js.map
  8233. var BABYLON;
  8234. (function (BABYLON) {
  8235. var PromiseStates;
  8236. (function (PromiseStates) {
  8237. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8238. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8239. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8240. })(PromiseStates || (PromiseStates = {}));
  8241. var FulFillmentAgregator = /** @class */ (function () {
  8242. function FulFillmentAgregator() {
  8243. this.count = 0;
  8244. this.target = 0;
  8245. this.results = [];
  8246. }
  8247. return FulFillmentAgregator;
  8248. }());
  8249. var InternalPromise = /** @class */ (function () {
  8250. function InternalPromise(resolver) {
  8251. var _this = this;
  8252. this._state = PromiseStates.Pending;
  8253. this._children = new Array();
  8254. this._rejectWasConsumed = false;
  8255. if (!resolver) {
  8256. return;
  8257. }
  8258. try {
  8259. resolver(function (value) {
  8260. _this._resolve(value);
  8261. }, function (reason) {
  8262. _this._reject(reason);
  8263. });
  8264. }
  8265. catch (e) {
  8266. this._reject(e.message);
  8267. }
  8268. }
  8269. Object.defineProperty(InternalPromise.prototype, "state", {
  8270. get: function () {
  8271. return this._state;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8277. get: function () {
  8278. return this._state === PromiseStates.Fulfilled;
  8279. },
  8280. enumerable: true,
  8281. configurable: true
  8282. });
  8283. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8284. get: function () {
  8285. return this._state === PromiseStates.Rejected;
  8286. },
  8287. enumerable: true,
  8288. configurable: true
  8289. });
  8290. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8291. get: function () {
  8292. return this._state === PromiseStates.Pending;
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. InternalPromise.prototype.value = function () {
  8298. if (!this.isFulfilled) {
  8299. throw new Error("Promise is not fulfilled");
  8300. }
  8301. return this._result;
  8302. };
  8303. InternalPromise.prototype.reason = function () {
  8304. if (!this.isRejected) {
  8305. throw new Error("Promise is not rejected");
  8306. }
  8307. return this._reason;
  8308. };
  8309. InternalPromise.prototype.catch = function (onRejected) {
  8310. return this.then(undefined, onRejected);
  8311. };
  8312. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8313. var newPromise = new InternalPromise();
  8314. newPromise._onFulfilled = onFulfilled;
  8315. newPromise._onRejected = onRejected;
  8316. // Composition
  8317. this._children.push(newPromise);
  8318. if (this._state !== PromiseStates.Pending) {
  8319. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8320. var returnedValue = newPromise._resolve(this._result);
  8321. if (returnedValue !== undefined && returnedValue !== null) {
  8322. if (returnedValue._state !== undefined) {
  8323. var returnedPromise = returnedValue;
  8324. newPromise._children.push(returnedPromise);
  8325. newPromise = returnedPromise;
  8326. }
  8327. else {
  8328. newPromise._result = returnedValue;
  8329. }
  8330. }
  8331. }
  8332. else {
  8333. newPromise._reject(this._reason);
  8334. }
  8335. }
  8336. return newPromise;
  8337. };
  8338. InternalPromise.prototype._moveChildren = function (children) {
  8339. this._children = children.splice(0, children.length);
  8340. if (this.isFulfilled) {
  8341. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8342. var child = _a[_i];
  8343. child._resolve(this._result);
  8344. }
  8345. }
  8346. else if (this.isRejected) {
  8347. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8348. var child = _c[_b];
  8349. child._reject(this._reason);
  8350. }
  8351. }
  8352. };
  8353. InternalPromise.prototype._resolve = function (value) {
  8354. try {
  8355. this._state = PromiseStates.Fulfilled;
  8356. this._result = value;
  8357. var returnedValue = null;
  8358. if (this._onFulfilled) {
  8359. returnedValue = this._onFulfilled(value);
  8360. }
  8361. if (returnedValue !== undefined && returnedValue !== null) {
  8362. if (returnedValue._state !== undefined) {
  8363. // Transmit children
  8364. var returnedPromise = returnedValue;
  8365. returnedPromise._moveChildren(this._children);
  8366. }
  8367. }
  8368. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8369. var child = _a[_i];
  8370. child._resolve(value);
  8371. }
  8372. return returnedValue;
  8373. }
  8374. catch (e) {
  8375. this._reject(e.message);
  8376. }
  8377. return null;
  8378. };
  8379. InternalPromise.prototype._reject = function (reason) {
  8380. this._state = PromiseStates.Rejected;
  8381. this._reason = reason;
  8382. if (this._onRejected) {
  8383. this._onRejected(reason);
  8384. this._rejectWasConsumed = true;
  8385. }
  8386. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8387. var child = _a[_i];
  8388. if (this._rejectWasConsumed) {
  8389. child._resolve(null);
  8390. }
  8391. else {
  8392. child._reject(reason);
  8393. }
  8394. }
  8395. };
  8396. InternalPromise.resolve = function (value) {
  8397. var newPromise = new InternalPromise();
  8398. newPromise._resolve(value);
  8399. return newPromise;
  8400. };
  8401. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8402. promise.then(function (value) {
  8403. agregator.results[index] = value;
  8404. agregator.count++;
  8405. if (agregator.count === agregator.target) {
  8406. agregator.rootPromise._resolve(agregator.results);
  8407. }
  8408. return null;
  8409. }, function (reason) {
  8410. if (!agregator.rootPromise.isRejected) {
  8411. agregator.rootPromise._reject(reason);
  8412. }
  8413. });
  8414. };
  8415. InternalPromise.all = function (promises) {
  8416. var newPromise = new InternalPromise();
  8417. var agregator = new FulFillmentAgregator();
  8418. agregator.target = promises.length;
  8419. agregator.rootPromise = newPromise;
  8420. for (var index = 0; index < promises.length; index++) {
  8421. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8422. }
  8423. return newPromise;
  8424. };
  8425. return InternalPromise;
  8426. }());
  8427. /**
  8428. * Helper class that provides a small promise polyfill
  8429. */
  8430. var PromisePolyfill = /** @class */ (function () {
  8431. function PromisePolyfill() {
  8432. }
  8433. /**
  8434. * Static function used to check if the polyfill is required
  8435. * If this is the case then the function will inject the polyfill to window.Promise
  8436. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8437. */
  8438. PromisePolyfill.Apply = function (force) {
  8439. if (force === void 0) { force = false; }
  8440. if (force || typeof Promise === 'undefined') {
  8441. var root = window;
  8442. root.Promise = InternalPromise;
  8443. }
  8444. };
  8445. return PromisePolyfill;
  8446. }());
  8447. BABYLON.PromisePolyfill = PromisePolyfill;
  8448. })(BABYLON || (BABYLON = {}));
  8449. //# sourceMappingURL=babylon.promise.js.map
  8450. var BABYLON;
  8451. (function (BABYLON) {
  8452. var _AlphaState = /** @class */ (function () {
  8453. /**
  8454. * Initializes the state.
  8455. */
  8456. function _AlphaState() {
  8457. this._isAlphaBlendDirty = false;
  8458. this._isBlendFunctionParametersDirty = false;
  8459. this._isBlendEquationParametersDirty = false;
  8460. this._isBlendConstantsDirty = false;
  8461. this._alphaBlend = false;
  8462. this._blendFunctionParameters = new Array(4);
  8463. this._blendEquationParameters = new Array(2);
  8464. this._blendConstants = new Array(4);
  8465. this.reset();
  8466. }
  8467. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8468. get: function () {
  8469. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8470. },
  8471. enumerable: true,
  8472. configurable: true
  8473. });
  8474. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8475. get: function () {
  8476. return this._alphaBlend;
  8477. },
  8478. set: function (value) {
  8479. if (this._alphaBlend === value) {
  8480. return;
  8481. }
  8482. this._alphaBlend = value;
  8483. this._isAlphaBlendDirty = true;
  8484. },
  8485. enumerable: true,
  8486. configurable: true
  8487. });
  8488. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8489. if (this._blendConstants[0] === r &&
  8490. this._blendConstants[1] === g &&
  8491. this._blendConstants[2] === b &&
  8492. this._blendConstants[3] === a) {
  8493. return;
  8494. }
  8495. this._blendConstants[0] = r;
  8496. this._blendConstants[1] = g;
  8497. this._blendConstants[2] = b;
  8498. this._blendConstants[3] = a;
  8499. this._isBlendConstantsDirty = true;
  8500. };
  8501. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8502. if (this._blendFunctionParameters[0] === value0 &&
  8503. this._blendFunctionParameters[1] === value1 &&
  8504. this._blendFunctionParameters[2] === value2 &&
  8505. this._blendFunctionParameters[3] === value3) {
  8506. return;
  8507. }
  8508. this._blendFunctionParameters[0] = value0;
  8509. this._blendFunctionParameters[1] = value1;
  8510. this._blendFunctionParameters[2] = value2;
  8511. this._blendFunctionParameters[3] = value3;
  8512. this._isBlendFunctionParametersDirty = true;
  8513. };
  8514. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8515. if (this._blendEquationParameters[0] === rgb &&
  8516. this._blendEquationParameters[1] === alpha) {
  8517. return;
  8518. }
  8519. this._blendEquationParameters[0] = rgb;
  8520. this._blendEquationParameters[1] = alpha;
  8521. this._isBlendEquationParametersDirty = true;
  8522. };
  8523. _AlphaState.prototype.reset = function () {
  8524. this._alphaBlend = false;
  8525. this._blendFunctionParameters[0] = null;
  8526. this._blendFunctionParameters[1] = null;
  8527. this._blendFunctionParameters[2] = null;
  8528. this._blendFunctionParameters[3] = null;
  8529. this._blendEquationParameters[0] = null;
  8530. this._blendEquationParameters[1] = null;
  8531. this._blendConstants[0] = null;
  8532. this._blendConstants[1] = null;
  8533. this._blendConstants[2] = null;
  8534. this._blendConstants[3] = null;
  8535. this._isAlphaBlendDirty = true;
  8536. this._isBlendFunctionParametersDirty = false;
  8537. this._isBlendEquationParametersDirty = false;
  8538. this._isBlendConstantsDirty = false;
  8539. };
  8540. _AlphaState.prototype.apply = function (gl) {
  8541. if (!this.isDirty) {
  8542. return;
  8543. }
  8544. // Alpha blend
  8545. if (this._isAlphaBlendDirty) {
  8546. if (this._alphaBlend) {
  8547. gl.enable(gl.BLEND);
  8548. }
  8549. else {
  8550. gl.disable(gl.BLEND);
  8551. }
  8552. this._isAlphaBlendDirty = false;
  8553. }
  8554. // Alpha function
  8555. if (this._isBlendFunctionParametersDirty) {
  8556. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8557. this._isBlendFunctionParametersDirty = false;
  8558. }
  8559. // Alpha equation
  8560. if (this._isBlendEquationParametersDirty) {
  8561. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8562. this._isBlendEquationParametersDirty = false;
  8563. }
  8564. // Constants
  8565. if (this._isBlendConstantsDirty) {
  8566. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8567. this._isBlendConstantsDirty = false;
  8568. }
  8569. };
  8570. return _AlphaState;
  8571. }());
  8572. BABYLON._AlphaState = _AlphaState;
  8573. })(BABYLON || (BABYLON = {}));
  8574. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8575. var BABYLON;
  8576. (function (BABYLON) {
  8577. var _DepthCullingState = /** @class */ (function () {
  8578. /**
  8579. * Initializes the state.
  8580. */
  8581. function _DepthCullingState() {
  8582. this._isDepthTestDirty = false;
  8583. this._isDepthMaskDirty = false;
  8584. this._isDepthFuncDirty = false;
  8585. this._isCullFaceDirty = false;
  8586. this._isCullDirty = false;
  8587. this._isZOffsetDirty = false;
  8588. this._isFrontFaceDirty = false;
  8589. this.reset();
  8590. }
  8591. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8592. get: function () {
  8593. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8594. },
  8595. enumerable: true,
  8596. configurable: true
  8597. });
  8598. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8599. get: function () {
  8600. return this._zOffset;
  8601. },
  8602. set: function (value) {
  8603. if (this._zOffset === value) {
  8604. return;
  8605. }
  8606. this._zOffset = value;
  8607. this._isZOffsetDirty = true;
  8608. },
  8609. enumerable: true,
  8610. configurable: true
  8611. });
  8612. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8613. get: function () {
  8614. return this._cullFace;
  8615. },
  8616. set: function (value) {
  8617. if (this._cullFace === value) {
  8618. return;
  8619. }
  8620. this._cullFace = value;
  8621. this._isCullFaceDirty = true;
  8622. },
  8623. enumerable: true,
  8624. configurable: true
  8625. });
  8626. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8627. get: function () {
  8628. return this._cull;
  8629. },
  8630. set: function (value) {
  8631. if (this._cull === value) {
  8632. return;
  8633. }
  8634. this._cull = value;
  8635. this._isCullDirty = true;
  8636. },
  8637. enumerable: true,
  8638. configurable: true
  8639. });
  8640. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8641. get: function () {
  8642. return this._depthFunc;
  8643. },
  8644. set: function (value) {
  8645. if (this._depthFunc === value) {
  8646. return;
  8647. }
  8648. this._depthFunc = value;
  8649. this._isDepthFuncDirty = true;
  8650. },
  8651. enumerable: true,
  8652. configurable: true
  8653. });
  8654. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8655. get: function () {
  8656. return this._depthMask;
  8657. },
  8658. set: function (value) {
  8659. if (this._depthMask === value) {
  8660. return;
  8661. }
  8662. this._depthMask = value;
  8663. this._isDepthMaskDirty = true;
  8664. },
  8665. enumerable: true,
  8666. configurable: true
  8667. });
  8668. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8669. get: function () {
  8670. return this._depthTest;
  8671. },
  8672. set: function (value) {
  8673. if (this._depthTest === value) {
  8674. return;
  8675. }
  8676. this._depthTest = value;
  8677. this._isDepthTestDirty = true;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8683. get: function () {
  8684. return this._frontFace;
  8685. },
  8686. set: function (value) {
  8687. if (this._frontFace === value) {
  8688. return;
  8689. }
  8690. this._frontFace = value;
  8691. this._isFrontFaceDirty = true;
  8692. },
  8693. enumerable: true,
  8694. configurable: true
  8695. });
  8696. _DepthCullingState.prototype.reset = function () {
  8697. this._depthMask = true;
  8698. this._depthTest = true;
  8699. this._depthFunc = null;
  8700. this._cullFace = null;
  8701. this._cull = null;
  8702. this._zOffset = 0;
  8703. this._frontFace = null;
  8704. this._isDepthTestDirty = true;
  8705. this._isDepthMaskDirty = true;
  8706. this._isDepthFuncDirty = false;
  8707. this._isCullFaceDirty = false;
  8708. this._isCullDirty = false;
  8709. this._isZOffsetDirty = false;
  8710. this._isFrontFaceDirty = false;
  8711. };
  8712. _DepthCullingState.prototype.apply = function (gl) {
  8713. if (!this.isDirty) {
  8714. return;
  8715. }
  8716. // Cull
  8717. if (this._isCullDirty) {
  8718. if (this.cull) {
  8719. gl.enable(gl.CULL_FACE);
  8720. }
  8721. else {
  8722. gl.disable(gl.CULL_FACE);
  8723. }
  8724. this._isCullDirty = false;
  8725. }
  8726. // Cull face
  8727. if (this._isCullFaceDirty) {
  8728. gl.cullFace(this.cullFace);
  8729. this._isCullFaceDirty = false;
  8730. }
  8731. // Depth mask
  8732. if (this._isDepthMaskDirty) {
  8733. gl.depthMask(this.depthMask);
  8734. this._isDepthMaskDirty = false;
  8735. }
  8736. // Depth test
  8737. if (this._isDepthTestDirty) {
  8738. if (this.depthTest) {
  8739. gl.enable(gl.DEPTH_TEST);
  8740. }
  8741. else {
  8742. gl.disable(gl.DEPTH_TEST);
  8743. }
  8744. this._isDepthTestDirty = false;
  8745. }
  8746. // Depth func
  8747. if (this._isDepthFuncDirty) {
  8748. gl.depthFunc(this.depthFunc);
  8749. this._isDepthFuncDirty = false;
  8750. }
  8751. // zOffset
  8752. if (this._isZOffsetDirty) {
  8753. if (this.zOffset) {
  8754. gl.enable(gl.POLYGON_OFFSET_FILL);
  8755. gl.polygonOffset(this.zOffset, 0);
  8756. }
  8757. else {
  8758. gl.disable(gl.POLYGON_OFFSET_FILL);
  8759. }
  8760. this._isZOffsetDirty = false;
  8761. }
  8762. // Front face
  8763. if (this._isFrontFaceDirty) {
  8764. gl.frontFace(this.frontFace);
  8765. this._isFrontFaceDirty = false;
  8766. }
  8767. };
  8768. return _DepthCullingState;
  8769. }());
  8770. BABYLON._DepthCullingState = _DepthCullingState;
  8771. })(BABYLON || (BABYLON = {}));
  8772. //# sourceMappingURL=babylon.depthCullingState.js.map
  8773. var BABYLON;
  8774. (function (BABYLON) {
  8775. var _StencilState = /** @class */ (function () {
  8776. function _StencilState() {
  8777. this._isStencilTestDirty = false;
  8778. this._isStencilMaskDirty = false;
  8779. this._isStencilFuncDirty = false;
  8780. this._isStencilOpDirty = false;
  8781. this.reset();
  8782. }
  8783. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8784. get: function () {
  8785. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8791. get: function () {
  8792. return this._stencilFunc;
  8793. },
  8794. set: function (value) {
  8795. if (this._stencilFunc === value) {
  8796. return;
  8797. }
  8798. this._stencilFunc = value;
  8799. this._isStencilFuncDirty = true;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8805. get: function () {
  8806. return this._stencilFuncRef;
  8807. },
  8808. set: function (value) {
  8809. if (this._stencilFuncRef === value) {
  8810. return;
  8811. }
  8812. this._stencilFuncRef = value;
  8813. this._isStencilFuncDirty = true;
  8814. },
  8815. enumerable: true,
  8816. configurable: true
  8817. });
  8818. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8819. get: function () {
  8820. return this._stencilFuncMask;
  8821. },
  8822. set: function (value) {
  8823. if (this._stencilFuncMask === value) {
  8824. return;
  8825. }
  8826. this._stencilFuncMask = value;
  8827. this._isStencilFuncDirty = true;
  8828. },
  8829. enumerable: true,
  8830. configurable: true
  8831. });
  8832. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8833. get: function () {
  8834. return this._stencilOpStencilFail;
  8835. },
  8836. set: function (value) {
  8837. if (this._stencilOpStencilFail === value) {
  8838. return;
  8839. }
  8840. this._stencilOpStencilFail = value;
  8841. this._isStencilOpDirty = true;
  8842. },
  8843. enumerable: true,
  8844. configurable: true
  8845. });
  8846. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8847. get: function () {
  8848. return this._stencilOpDepthFail;
  8849. },
  8850. set: function (value) {
  8851. if (this._stencilOpDepthFail === value) {
  8852. return;
  8853. }
  8854. this._stencilOpDepthFail = value;
  8855. this._isStencilOpDirty = true;
  8856. },
  8857. enumerable: true,
  8858. configurable: true
  8859. });
  8860. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8861. get: function () {
  8862. return this._stencilOpStencilDepthPass;
  8863. },
  8864. set: function (value) {
  8865. if (this._stencilOpStencilDepthPass === value) {
  8866. return;
  8867. }
  8868. this._stencilOpStencilDepthPass = value;
  8869. this._isStencilOpDirty = true;
  8870. },
  8871. enumerable: true,
  8872. configurable: true
  8873. });
  8874. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8875. get: function () {
  8876. return this._stencilMask;
  8877. },
  8878. set: function (value) {
  8879. if (this._stencilMask === value) {
  8880. return;
  8881. }
  8882. this._stencilMask = value;
  8883. this._isStencilMaskDirty = true;
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8889. get: function () {
  8890. return this._stencilTest;
  8891. },
  8892. set: function (value) {
  8893. if (this._stencilTest === value) {
  8894. return;
  8895. }
  8896. this._stencilTest = value;
  8897. this._isStencilTestDirty = true;
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. _StencilState.prototype.reset = function () {
  8903. this._stencilTest = false;
  8904. this._stencilMask = 0xFF;
  8905. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8906. this._stencilFuncRef = 1;
  8907. this._stencilFuncMask = 0xFF;
  8908. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8909. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8910. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8911. this._isStencilTestDirty = true;
  8912. this._isStencilMaskDirty = true;
  8913. this._isStencilFuncDirty = true;
  8914. this._isStencilOpDirty = true;
  8915. };
  8916. _StencilState.prototype.apply = function (gl) {
  8917. if (!this.isDirty) {
  8918. return;
  8919. }
  8920. // Stencil test
  8921. if (this._isStencilTestDirty) {
  8922. if (this.stencilTest) {
  8923. gl.enable(gl.STENCIL_TEST);
  8924. }
  8925. else {
  8926. gl.disable(gl.STENCIL_TEST);
  8927. }
  8928. this._isStencilTestDirty = false;
  8929. }
  8930. // Stencil mask
  8931. if (this._isStencilMaskDirty) {
  8932. gl.stencilMask(this.stencilMask);
  8933. this._isStencilMaskDirty = false;
  8934. }
  8935. // Stencil func
  8936. if (this._isStencilFuncDirty) {
  8937. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8938. this._isStencilFuncDirty = false;
  8939. }
  8940. // Stencil op
  8941. if (this._isStencilOpDirty) {
  8942. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8943. this._isStencilOpDirty = false;
  8944. }
  8945. };
  8946. return _StencilState;
  8947. }());
  8948. BABYLON._StencilState = _StencilState;
  8949. })(BABYLON || (BABYLON = {}));
  8950. //# sourceMappingURL=babylon.stencilState.js.map
  8951. var BABYLON;
  8952. (function (BABYLON) {
  8953. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8954. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8955. };
  8956. var compileRawShader = function (gl, source, type) {
  8957. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8958. gl.shaderSource(shader, source);
  8959. gl.compileShader(shader);
  8960. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8961. var log = gl.getShaderInfoLog(shader);
  8962. if (log) {
  8963. throw new Error(log);
  8964. }
  8965. }
  8966. if (!shader) {
  8967. throw new Error("Something went wrong while compile the shader.");
  8968. }
  8969. return shader;
  8970. };
  8971. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8972. var magFilter = gl.NEAREST;
  8973. var minFilter = gl.NEAREST;
  8974. switch (samplingMode) {
  8975. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8976. magFilter = gl.LINEAR;
  8977. if (generateMipMaps) {
  8978. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8979. }
  8980. else {
  8981. minFilter = gl.LINEAR;
  8982. }
  8983. break;
  8984. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8985. magFilter = gl.LINEAR;
  8986. if (generateMipMaps) {
  8987. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8988. }
  8989. else {
  8990. minFilter = gl.LINEAR;
  8991. }
  8992. break;
  8993. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8994. magFilter = gl.NEAREST;
  8995. if (generateMipMaps) {
  8996. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8997. }
  8998. else {
  8999. minFilter = gl.NEAREST;
  9000. }
  9001. break;
  9002. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9003. magFilter = gl.NEAREST;
  9004. if (generateMipMaps) {
  9005. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9006. }
  9007. else {
  9008. minFilter = gl.NEAREST;
  9009. }
  9010. break;
  9011. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9012. magFilter = gl.NEAREST;
  9013. if (generateMipMaps) {
  9014. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9015. }
  9016. else {
  9017. minFilter = gl.LINEAR;
  9018. }
  9019. break;
  9020. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9021. magFilter = gl.NEAREST;
  9022. if (generateMipMaps) {
  9023. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9024. }
  9025. else {
  9026. minFilter = gl.LINEAR;
  9027. }
  9028. break;
  9029. case BABYLON.Texture.NEAREST_LINEAR:
  9030. magFilter = gl.NEAREST;
  9031. minFilter = gl.LINEAR;
  9032. break;
  9033. case BABYLON.Texture.NEAREST_NEAREST:
  9034. magFilter = gl.NEAREST;
  9035. minFilter = gl.NEAREST;
  9036. break;
  9037. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9038. magFilter = gl.LINEAR;
  9039. if (generateMipMaps) {
  9040. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9041. }
  9042. else {
  9043. minFilter = gl.NEAREST;
  9044. }
  9045. break;
  9046. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9047. magFilter = gl.LINEAR;
  9048. if (generateMipMaps) {
  9049. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9050. }
  9051. else {
  9052. minFilter = gl.NEAREST;
  9053. }
  9054. break;
  9055. case BABYLON.Texture.LINEAR_LINEAR:
  9056. magFilter = gl.LINEAR;
  9057. minFilter = gl.LINEAR;
  9058. break;
  9059. case BABYLON.Texture.LINEAR_NEAREST:
  9060. magFilter = gl.LINEAR;
  9061. minFilter = gl.NEAREST;
  9062. break;
  9063. }
  9064. return {
  9065. min: minFilter,
  9066. mag: magFilter
  9067. };
  9068. };
  9069. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9070. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9071. var img;
  9072. var onload = function () {
  9073. loadedImages[index] = img;
  9074. loadedImages._internalCount++;
  9075. if (scene) {
  9076. scene._removePendingData(img);
  9077. }
  9078. if (loadedImages._internalCount === 6) {
  9079. onfinish(loadedImages);
  9080. }
  9081. };
  9082. var onerror = function (message, exception) {
  9083. if (scene) {
  9084. scene._removePendingData(img);
  9085. }
  9086. if (onErrorCallBack) {
  9087. onErrorCallBack(message, exception);
  9088. }
  9089. };
  9090. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9091. if (scene) {
  9092. scene._addPendingData(img);
  9093. }
  9094. };
  9095. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9096. if (onError === void 0) { onError = null; }
  9097. var loadedImages = [];
  9098. loadedImages._internalCount = 0;
  9099. for (var index = 0; index < 6; index++) {
  9100. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9101. }
  9102. };
  9103. var BufferPointer = /** @class */ (function () {
  9104. function BufferPointer() {
  9105. }
  9106. return BufferPointer;
  9107. }());
  9108. var InstancingAttributeInfo = /** @class */ (function () {
  9109. function InstancingAttributeInfo() {
  9110. }
  9111. return InstancingAttributeInfo;
  9112. }());
  9113. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9114. /**
  9115. * Define options used to create a render target texture
  9116. */
  9117. var RenderTargetCreationOptions = /** @class */ (function () {
  9118. function RenderTargetCreationOptions() {
  9119. }
  9120. return RenderTargetCreationOptions;
  9121. }());
  9122. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9123. /**
  9124. * Regroup several parameters relative to the browser in use
  9125. */
  9126. var EngineCapabilities = /** @class */ (function () {
  9127. function EngineCapabilities() {
  9128. }
  9129. return EngineCapabilities;
  9130. }());
  9131. BABYLON.EngineCapabilities = EngineCapabilities;
  9132. /**
  9133. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9134. */
  9135. var Engine = /** @class */ (function () {
  9136. /**
  9137. * @constructor
  9138. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9139. * @param antialias defines enable antialiasing (default: false)
  9140. * @param options defines further options to be sent to the getContext() function
  9141. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9142. */
  9143. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9144. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9145. var _this = this;
  9146. // Public members
  9147. this.forcePOTTextures = false;
  9148. this.isFullscreen = false;
  9149. this.isPointerLock = false;
  9150. this.cullBackFaces = true;
  9151. this.renderEvenInBackground = true;
  9152. this.preventCacheWipeBetweenFrames = false;
  9153. // To enable/disable IDB support and avoid XHR on .manifest
  9154. this.enableOfflineSupport = false;
  9155. this.scenes = new Array();
  9156. this.postProcesses = new Array();
  9157. // Observables
  9158. /**
  9159. * Observable event triggered each time the rendering canvas is resized
  9160. */
  9161. this.onResizeObservable = new BABYLON.Observable();
  9162. /**
  9163. * Observable event triggered each time the canvas loses focus
  9164. */
  9165. this.onCanvasBlurObservable = new BABYLON.Observable();
  9166. /**
  9167. * Observable event triggered each time the canvas gains focus
  9168. */
  9169. this.onCanvasFocusObservable = new BABYLON.Observable();
  9170. /**
  9171. * Observable event triggered each time the canvas receives pointerout event
  9172. */
  9173. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9174. /**
  9175. * Observable event triggered before each texture is initialized
  9176. */
  9177. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9178. //WebVR
  9179. this._vrDisplay = undefined;
  9180. this._vrSupported = false;
  9181. this._vrExclusivePointerMode = false;
  9182. // Uniform buffers list
  9183. this.disableUniformBuffers = false;
  9184. this._uniformBuffers = new Array();
  9185. // Observables
  9186. /**
  9187. * Observable raised when the engine begins a new frame
  9188. */
  9189. this.onBeginFrameObservable = new BABYLON.Observable();
  9190. /**
  9191. * Observable raised when the engine ends the current frame
  9192. */
  9193. this.onEndFrameObservable = new BABYLON.Observable();
  9194. /**
  9195. * Observable raised when the engine is about to compile a shader
  9196. */
  9197. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9198. /**
  9199. * Observable raised when the engine has jsut compiled a shader
  9200. */
  9201. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9202. this._windowIsBackground = false;
  9203. this._webGLVersion = 1.0;
  9204. this._badOS = false;
  9205. this._badDesktopOS = false;
  9206. /**
  9207. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9208. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9209. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9210. */
  9211. this.disableTextureBindingOptimization = false;
  9212. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9213. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9214. this.onVRRequestPresentStart = new BABYLON.Observable();
  9215. this._colorWrite = true;
  9216. this._drawCalls = new BABYLON.PerfCounter();
  9217. this._textureCollisions = new BABYLON.PerfCounter();
  9218. this._renderingQueueLaunched = false;
  9219. this._activeRenderLoops = new Array();
  9220. // Deterministic lockstepMaxSteps
  9221. this._deterministicLockstep = false;
  9222. this._lockstepMaxSteps = 4;
  9223. // Lost context
  9224. this.onContextLostObservable = new BABYLON.Observable();
  9225. this.onContextRestoredObservable = new BABYLON.Observable();
  9226. this._contextWasLost = false;
  9227. this._doNotHandleContextLost = false;
  9228. // FPS
  9229. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9230. this._fps = 60;
  9231. this._deltaTime = 0;
  9232. /**
  9233. * Turn this value on if you want to pause FPS computation when in background
  9234. */
  9235. this.disablePerformanceMonitorInBackground = false;
  9236. // States
  9237. this._depthCullingState = new BABYLON._DepthCullingState();
  9238. this._stencilState = new BABYLON._StencilState();
  9239. this._alphaState = new BABYLON._AlphaState();
  9240. this._alphaMode = Engine.ALPHA_DISABLE;
  9241. // Cache
  9242. this._internalTexturesCache = new Array();
  9243. this._activeChannel = 0;
  9244. this._currentTextureChannel = -1;
  9245. this._boundTexturesCache = {};
  9246. this._compiledEffects = {};
  9247. this._vertexAttribArraysEnabled = [];
  9248. this._uintIndicesCurrentlySet = false;
  9249. this._currentBoundBuffer = new Array();
  9250. this._currentBufferPointers = new Array();
  9251. this._currentInstanceLocations = new Array();
  9252. this._currentInstanceBuffers = new Array();
  9253. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9254. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9255. this._vaoRecordInProgress = false;
  9256. this._mustWipeVertexAttributes = false;
  9257. this._nextFreeTextureSlots = new Array();
  9258. this._maxSimultaneousTextures = 0;
  9259. this._activeRequests = new Array();
  9260. // Hardware supported Compressed Textures
  9261. this._texturesSupported = new Array();
  9262. this._onVRFullScreenTriggered = function () {
  9263. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9264. //get the old size before we change
  9265. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9266. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9267. //get the width and height, change the render size
  9268. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9269. _this.setHardwareScalingLevel(1);
  9270. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9271. }
  9272. else {
  9273. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9274. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9275. }
  9276. };
  9277. this._boundUniforms = {};
  9278. // Register promises
  9279. BABYLON.PromisePolyfill.Apply();
  9280. var canvas = null;
  9281. Engine.Instances.push(this);
  9282. if (!canvasOrContext) {
  9283. return;
  9284. }
  9285. options = options || {};
  9286. if (canvasOrContext.getContext) {
  9287. canvas = canvasOrContext;
  9288. this._renderingCanvas = canvas;
  9289. if (antialias != null) {
  9290. options.antialias = antialias;
  9291. }
  9292. if (options.deterministicLockstep === undefined) {
  9293. options.deterministicLockstep = false;
  9294. }
  9295. if (options.lockstepMaxSteps === undefined) {
  9296. options.lockstepMaxSteps = 4;
  9297. }
  9298. if (options.preserveDrawingBuffer === undefined) {
  9299. options.preserveDrawingBuffer = false;
  9300. }
  9301. if (options.audioEngine === undefined) {
  9302. options.audioEngine = true;
  9303. }
  9304. if (options.stencil === undefined) {
  9305. options.stencil = true;
  9306. }
  9307. this._deterministicLockstep = options.deterministicLockstep;
  9308. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9309. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9310. // Exceptions
  9311. if (navigator && navigator.userAgent) {
  9312. var ua = navigator.userAgent;
  9313. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9314. var exception = _a[_i];
  9315. var key = exception.key;
  9316. var targets = exception.targets;
  9317. if (ua.indexOf(key) > -1) {
  9318. if (exception.capture && exception.captureConstraint) {
  9319. var capture = exception.capture;
  9320. var constraint = exception.captureConstraint;
  9321. var regex = new RegExp(capture);
  9322. var matches = regex.exec(ua);
  9323. if (matches && matches.length > 0) {
  9324. var capturedValue = parseInt(matches[matches.length - 1]);
  9325. if (capturedValue >= constraint) {
  9326. continue;
  9327. }
  9328. }
  9329. }
  9330. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9331. var target = targets_1[_b];
  9332. switch (target) {
  9333. case "uniformBuffer":
  9334. this.disableUniformBuffers = true;
  9335. break;
  9336. case "textureBindingOptimization":
  9337. this.disableTextureBindingOptimization = true;
  9338. break;
  9339. }
  9340. }
  9341. break;
  9342. }
  9343. }
  9344. }
  9345. // GL
  9346. if (!options.disableWebGL2Support) {
  9347. try {
  9348. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9349. if (this._gl) {
  9350. this._webGLVersion = 2.0;
  9351. }
  9352. }
  9353. catch (e) {
  9354. // Do nothing
  9355. }
  9356. }
  9357. if (!this._gl) {
  9358. if (!canvas) {
  9359. throw new Error("The provided canvas is null or undefined.");
  9360. }
  9361. try {
  9362. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9363. }
  9364. catch (e) {
  9365. throw new Error("WebGL not supported");
  9366. }
  9367. }
  9368. if (!this._gl) {
  9369. throw new Error("WebGL not supported");
  9370. }
  9371. this._onCanvasFocus = function () {
  9372. _this.onCanvasFocusObservable.notifyObservers(_this);
  9373. };
  9374. this._onCanvasBlur = function () {
  9375. _this.onCanvasBlurObservable.notifyObservers(_this);
  9376. };
  9377. canvas.addEventListener("focus", this._onCanvasFocus);
  9378. canvas.addEventListener("blur", this._onCanvasBlur);
  9379. this._onBlur = function () {
  9380. if (_this.disablePerformanceMonitorInBackground) {
  9381. _this._performanceMonitor.disable();
  9382. }
  9383. _this._windowIsBackground = true;
  9384. };
  9385. this._onFocus = function () {
  9386. if (_this.disablePerformanceMonitorInBackground) {
  9387. _this._performanceMonitor.enable();
  9388. }
  9389. _this._windowIsBackground = false;
  9390. };
  9391. this._onCanvasPointerOut = function () {
  9392. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9393. };
  9394. window.addEventListener("blur", this._onBlur);
  9395. window.addEventListener("focus", this._onFocus);
  9396. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9397. // Context lost
  9398. if (!this._doNotHandleContextLost) {
  9399. this._onContextLost = function (evt) {
  9400. evt.preventDefault();
  9401. _this._contextWasLost = true;
  9402. BABYLON.Tools.Warn("WebGL context lost.");
  9403. _this.onContextLostObservable.notifyObservers(_this);
  9404. };
  9405. this._onContextRestored = function (evt) {
  9406. // Adding a timeout to avoid race condition at browser level
  9407. setTimeout(function () {
  9408. // Rebuild gl context
  9409. _this._initGLContext();
  9410. // Rebuild effects
  9411. _this._rebuildEffects();
  9412. // Rebuild textures
  9413. _this._rebuildInternalTextures();
  9414. // Rebuild buffers
  9415. _this._rebuildBuffers();
  9416. // Cache
  9417. _this.wipeCaches(true);
  9418. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9419. _this.onContextRestoredObservable.notifyObservers(_this);
  9420. _this._contextWasLost = false;
  9421. }, 0);
  9422. };
  9423. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9424. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9425. }
  9426. }
  9427. else {
  9428. this._gl = canvasOrContext;
  9429. this._renderingCanvas = this._gl.canvas;
  9430. if (this._gl.renderbufferStorageMultisample) {
  9431. this._webGLVersion = 2.0;
  9432. }
  9433. options.stencil = this._gl.getContextAttributes().stencil;
  9434. }
  9435. // Viewport
  9436. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9437. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9438. this.resize();
  9439. this._isStencilEnable = options.stencil ? true : false;
  9440. this._initGLContext();
  9441. if (canvas) {
  9442. // Fullscreen
  9443. this._onFullscreenChange = function () {
  9444. if (document.fullscreen !== undefined) {
  9445. _this.isFullscreen = document.fullscreen;
  9446. }
  9447. else if (document.mozFullScreen !== undefined) {
  9448. _this.isFullscreen = document.mozFullScreen;
  9449. }
  9450. else if (document.webkitIsFullScreen !== undefined) {
  9451. _this.isFullscreen = document.webkitIsFullScreen;
  9452. }
  9453. else if (document.msIsFullScreen !== undefined) {
  9454. _this.isFullscreen = document.msIsFullScreen;
  9455. }
  9456. // Pointer lock
  9457. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9458. canvas.requestPointerLock = canvas.requestPointerLock ||
  9459. canvas.msRequestPointerLock ||
  9460. canvas.mozRequestPointerLock ||
  9461. canvas.webkitRequestPointerLock;
  9462. if (canvas.requestPointerLock) {
  9463. canvas.requestPointerLock();
  9464. }
  9465. }
  9466. };
  9467. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9468. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9469. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9470. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9471. // Pointer lock
  9472. this._onPointerLockChange = function () {
  9473. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9474. document.webkitPointerLockElement === canvas ||
  9475. document.msPointerLockElement === canvas ||
  9476. document.pointerLockElement === canvas);
  9477. };
  9478. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9479. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9480. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9481. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9482. this._onVRDisplayPointerRestricted = function () {
  9483. if (canvas) {
  9484. canvas.requestPointerLock();
  9485. }
  9486. };
  9487. this._onVRDisplayPointerUnrestricted = function () {
  9488. document.exitPointerLock();
  9489. };
  9490. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9491. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9492. }
  9493. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9494. Engine.audioEngine = new BABYLON.AudioEngine();
  9495. }
  9496. // Prepare buffer pointers
  9497. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9498. this._currentBufferPointers[i] = new BufferPointer();
  9499. }
  9500. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9501. // Load WebVR Devices
  9502. if (options.autoEnableWebVR) {
  9503. this.initWebVR();
  9504. }
  9505. // Detect if we are running on a faulty buggy OS.
  9506. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9507. // Detect if we are running on a faulty buggy desktop OS.
  9508. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9509. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9510. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9511. }
  9512. Object.defineProperty(Engine, "LastCreatedEngine", {
  9513. get: function () {
  9514. if (Engine.Instances.length === 0) {
  9515. return null;
  9516. }
  9517. return Engine.Instances[Engine.Instances.length - 1];
  9518. },
  9519. enumerable: true,
  9520. configurable: true
  9521. });
  9522. Object.defineProperty(Engine, "LastCreatedScene", {
  9523. get: function () {
  9524. var lastCreatedEngine = Engine.LastCreatedEngine;
  9525. if (!lastCreatedEngine) {
  9526. return null;
  9527. }
  9528. if (lastCreatedEngine.scenes.length === 0) {
  9529. return null;
  9530. }
  9531. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. /**
  9537. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9538. */
  9539. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9540. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9541. var engine = Engine.Instances[engineIndex];
  9542. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9543. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9544. }
  9545. }
  9546. };
  9547. Object.defineProperty(Engine, "NEVER", {
  9548. get: function () {
  9549. return Engine._NEVER;
  9550. },
  9551. enumerable: true,
  9552. configurable: true
  9553. });
  9554. Object.defineProperty(Engine, "ALWAYS", {
  9555. get: function () {
  9556. return Engine._ALWAYS;
  9557. },
  9558. enumerable: true,
  9559. configurable: true
  9560. });
  9561. Object.defineProperty(Engine, "LESS", {
  9562. get: function () {
  9563. return Engine._LESS;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Object.defineProperty(Engine, "EQUAL", {
  9569. get: function () {
  9570. return Engine._EQUAL;
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(Engine, "LEQUAL", {
  9576. get: function () {
  9577. return Engine._LEQUAL;
  9578. },
  9579. enumerable: true,
  9580. configurable: true
  9581. });
  9582. Object.defineProperty(Engine, "GREATER", {
  9583. get: function () {
  9584. return Engine._GREATER;
  9585. },
  9586. enumerable: true,
  9587. configurable: true
  9588. });
  9589. Object.defineProperty(Engine, "GEQUAL", {
  9590. get: function () {
  9591. return Engine._GEQUAL;
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Object.defineProperty(Engine, "NOTEQUAL", {
  9597. get: function () {
  9598. return Engine._NOTEQUAL;
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(Engine, "KEEP", {
  9604. get: function () {
  9605. return Engine._KEEP;
  9606. },
  9607. enumerable: true,
  9608. configurable: true
  9609. });
  9610. Object.defineProperty(Engine, "REPLACE", {
  9611. get: function () {
  9612. return Engine._REPLACE;
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. Object.defineProperty(Engine, "INCR", {
  9618. get: function () {
  9619. return Engine._INCR;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. Object.defineProperty(Engine, "DECR", {
  9625. get: function () {
  9626. return Engine._DECR;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Engine, "INVERT", {
  9632. get: function () {
  9633. return Engine._INVERT;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Engine, "INCR_WRAP", {
  9639. get: function () {
  9640. return Engine._INCR_WRAP;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Engine, "DECR_WRAP", {
  9646. get: function () {
  9647. return Engine._DECR_WRAP;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9653. get: function () {
  9654. return Engine._ALPHA_DISABLE;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9660. get: function () {
  9661. return Engine._ALPHA_ONEONE;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Engine, "ALPHA_ADD", {
  9667. get: function () {
  9668. return Engine._ALPHA_ADD;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9674. get: function () {
  9675. return Engine._ALPHA_COMBINE;
  9676. },
  9677. enumerable: true,
  9678. configurable: true
  9679. });
  9680. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9681. get: function () {
  9682. return Engine._ALPHA_SUBTRACT;
  9683. },
  9684. enumerable: true,
  9685. configurable: true
  9686. });
  9687. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9688. get: function () {
  9689. return Engine._ALPHA_MULTIPLY;
  9690. },
  9691. enumerable: true,
  9692. configurable: true
  9693. });
  9694. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9695. get: function () {
  9696. return Engine._ALPHA_MAXIMIZED;
  9697. },
  9698. enumerable: true,
  9699. configurable: true
  9700. });
  9701. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9702. get: function () {
  9703. return Engine._ALPHA_PREMULTIPLIED;
  9704. },
  9705. enumerable: true,
  9706. configurable: true
  9707. });
  9708. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9709. get: function () {
  9710. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9711. },
  9712. enumerable: true,
  9713. configurable: true
  9714. });
  9715. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9716. get: function () {
  9717. return Engine._ALPHA_INTERPOLATE;
  9718. },
  9719. enumerable: true,
  9720. configurable: true
  9721. });
  9722. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9723. get: function () {
  9724. return Engine._ALPHA_SCREENMODE;
  9725. },
  9726. enumerable: true,
  9727. configurable: true
  9728. });
  9729. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9730. get: function () {
  9731. return Engine._DELAYLOADSTATE_NONE;
  9732. },
  9733. enumerable: true,
  9734. configurable: true
  9735. });
  9736. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9737. get: function () {
  9738. return Engine._DELAYLOADSTATE_LOADED;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9744. get: function () {
  9745. return Engine._DELAYLOADSTATE_LOADING;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9751. get: function () {
  9752. return Engine._DELAYLOADSTATE_NOTLOADED;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9758. get: function () {
  9759. return Engine._TEXTUREFORMAT_ALPHA;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9765. get: function () {
  9766. return Engine._TEXTUREFORMAT_LUMINANCE;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9772. get: function () {
  9773. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9774. },
  9775. enumerable: true,
  9776. configurable: true
  9777. });
  9778. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9779. get: function () {
  9780. return Engine._TEXTUREFORMAT_RGB;
  9781. },
  9782. enumerable: true,
  9783. configurable: true
  9784. });
  9785. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9786. get: function () {
  9787. return Engine._TEXTUREFORMAT_RGBA;
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9793. get: function () {
  9794. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9800. get: function () {
  9801. return Engine._TEXTURETYPE_FLOAT;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9807. get: function () {
  9808. return Engine._TEXTURETYPE_HALF_FLOAT;
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9814. get: function () {
  9815. return Engine._SCALEMODE_FLOOR;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9821. get: function () {
  9822. return Engine._SCALEMODE_NEAREST;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9828. get: function () {
  9829. return Engine._SCALEMODE_CEILING;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(Engine, "Version", {
  9835. get: function () {
  9836. return "3.2.0-alpha6";
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9842. get: function () {
  9843. return this._vrExclusivePointerMode;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9849. get: function () {
  9850. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9856. get: function () {
  9857. return this._webGLVersion < 2 || this.forcePOTTextures;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(Engine.prototype, "badOS", {
  9863. get: function () {
  9864. return this._badOS;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9870. get: function () {
  9871. return this._badDesktopOS;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9877. get: function () {
  9878. return this._performanceMonitor;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9884. get: function () {
  9885. return this._texturesSupported;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9891. get: function () {
  9892. return this._textureFormatInUse;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(Engine.prototype, "currentViewport", {
  9898. get: function () {
  9899. return this._cachedViewport;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9905. // Empty texture
  9906. get: function () {
  9907. if (!this._emptyTexture) {
  9908. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9909. }
  9910. return this._emptyTexture;
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9916. get: function () {
  9917. if (!this._emptyTexture3D) {
  9918. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9919. }
  9920. return this._emptyTexture3D;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9926. get: function () {
  9927. if (!this._emptyCubeTexture) {
  9928. var faceData = new Uint8Array(4);
  9929. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9930. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9931. }
  9932. return this._emptyCubeTexture;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. Engine.prototype._rebuildInternalTextures = function () {
  9938. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9939. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9940. var internalTexture = currentState_1[_i];
  9941. internalTexture._rebuild();
  9942. }
  9943. };
  9944. Engine.prototype._rebuildEffects = function () {
  9945. for (var key in this._compiledEffects) {
  9946. var effect = this._compiledEffects[key];
  9947. effect._prepareEffect();
  9948. }
  9949. BABYLON.Effect.ResetCache();
  9950. };
  9951. Engine.prototype._rebuildBuffers = function () {
  9952. // Index / Vertex
  9953. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9954. var scene = _a[_i];
  9955. scene.resetCachedMaterial();
  9956. scene._rebuildGeometries();
  9957. scene._rebuildTextures();
  9958. }
  9959. // Uniforms
  9960. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9961. var uniformBuffer = _c[_b];
  9962. uniformBuffer._rebuild();
  9963. }
  9964. };
  9965. Engine.prototype._initGLContext = function () {
  9966. // Caps
  9967. this._caps = new EngineCapabilities();
  9968. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9969. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9970. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9971. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9972. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9973. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9974. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9975. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9976. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9977. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9978. // Infos
  9979. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9980. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9981. if (rendererInfo != null) {
  9982. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9983. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9984. }
  9985. if (!this._glVendor) {
  9986. this._glVendor = "Unknown vendor";
  9987. }
  9988. if (!this._glRenderer) {
  9989. this._glRenderer = "Unknown renderer";
  9990. }
  9991. // Constants
  9992. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9993. if (this._gl.RGBA16F !== 0x881A) {
  9994. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9995. }
  9996. if (this._gl.RGBA32F !== 0x8814) {
  9997. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9998. }
  9999. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10000. this._gl.DEPTH24_STENCIL8 = 35056;
  10001. }
  10002. // Extensions
  10003. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10004. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10005. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10006. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10007. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10008. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10009. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10010. 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');
  10011. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10012. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10013. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10014. this._caps.highPrecisionShaderSupported = true;
  10015. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10016. if (this._caps.timerQuery) {
  10017. if (this._webGLVersion === 1) {
  10018. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10019. }
  10020. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10021. }
  10022. // Checks if some of the format renders first to allow the use of webgl inspector.
  10023. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10024. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10025. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10026. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10027. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10028. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10029. if (this._webGLVersion > 1) {
  10030. this._gl.HALF_FLOAT_OES = 0x140B;
  10031. }
  10032. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10033. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10034. // Draw buffers
  10035. if (this._webGLVersion > 1) {
  10036. this._caps.drawBuffersExtension = true;
  10037. }
  10038. else {
  10039. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10040. if (drawBuffersExtension !== null) {
  10041. this._caps.drawBuffersExtension = true;
  10042. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10043. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10044. for (var i = 0; i < 16; i++) {
  10045. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10046. }
  10047. }
  10048. else {
  10049. this._caps.drawBuffersExtension = false;
  10050. }
  10051. }
  10052. // Depth Texture
  10053. if (this._webGLVersion > 1) {
  10054. this._caps.depthTextureExtension = true;
  10055. }
  10056. else {
  10057. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10058. if (depthTextureExtension != null) {
  10059. this._caps.depthTextureExtension = true;
  10060. }
  10061. }
  10062. // Vertex array object
  10063. if (this._webGLVersion > 1) {
  10064. this._caps.vertexArrayObject = true;
  10065. }
  10066. else {
  10067. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10068. if (vertexArrayObjectExtension != null) {
  10069. this._caps.vertexArrayObject = true;
  10070. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10071. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10072. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10073. }
  10074. else {
  10075. this._caps.vertexArrayObject = false;
  10076. }
  10077. }
  10078. // Instances count
  10079. if (this._webGLVersion > 1) {
  10080. this._caps.instancedArrays = true;
  10081. }
  10082. else {
  10083. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10084. if (instanceExtension != null) {
  10085. this._caps.instancedArrays = true;
  10086. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10087. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10088. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10089. }
  10090. else {
  10091. this._caps.instancedArrays = false;
  10092. }
  10093. }
  10094. // Intelligently add supported compressed formats in order to check for.
  10095. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10096. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10097. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10098. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10099. if (this._caps.astc)
  10100. this.texturesSupported.push('-astc.ktx');
  10101. if (this._caps.s3tc)
  10102. this.texturesSupported.push('-dxt.ktx');
  10103. if (this._caps.pvrtc)
  10104. this.texturesSupported.push('-pvrtc.ktx');
  10105. if (this._caps.etc2)
  10106. this.texturesSupported.push('-etc2.ktx');
  10107. if (this._caps.etc1)
  10108. this.texturesSupported.push('-etc1.ktx');
  10109. if (this._gl.getShaderPrecisionFormat) {
  10110. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10111. if (highp) {
  10112. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10113. }
  10114. }
  10115. // Depth buffer
  10116. this.setDepthBuffer(true);
  10117. this.setDepthFunctionToLessOrEqual();
  10118. this.setDepthWrite(true);
  10119. // Texture maps
  10120. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10121. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10122. this._nextFreeTextureSlots.push(slot);
  10123. }
  10124. };
  10125. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10126. get: function () {
  10127. return this._webGLVersion;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10133. /**
  10134. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10135. */
  10136. get: function () {
  10137. return this._isStencilEnable;
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. Engine.prototype._prepareWorkingCanvas = function () {
  10143. if (this._workingCanvas) {
  10144. return;
  10145. }
  10146. this._workingCanvas = document.createElement("canvas");
  10147. var context = this._workingCanvas.getContext("2d");
  10148. if (context) {
  10149. this._workingContext = context;
  10150. }
  10151. };
  10152. Engine.prototype.resetTextureCache = function () {
  10153. for (var key in this._boundTexturesCache) {
  10154. var boundTexture = this._boundTexturesCache[key];
  10155. if (boundTexture) {
  10156. this._removeDesignatedSlot(boundTexture);
  10157. }
  10158. this._boundTexturesCache[key] = null;
  10159. }
  10160. this._nextFreeTextureSlots = [];
  10161. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10162. this._nextFreeTextureSlots.push(slot);
  10163. }
  10164. this._currentTextureChannel = -1;
  10165. };
  10166. Engine.prototype.isDeterministicLockStep = function () {
  10167. return this._deterministicLockstep;
  10168. };
  10169. Engine.prototype.getLockstepMaxSteps = function () {
  10170. return this._lockstepMaxSteps;
  10171. };
  10172. Engine.prototype.getGlInfo = function () {
  10173. return {
  10174. vendor: this._glVendor,
  10175. renderer: this._glRenderer,
  10176. version: this._glVersion
  10177. };
  10178. };
  10179. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10180. if (useScreen === void 0) { useScreen = false; }
  10181. var viewport = camera.viewport;
  10182. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10183. };
  10184. Engine.prototype.getRenderWidth = function (useScreen) {
  10185. if (useScreen === void 0) { useScreen = false; }
  10186. if (!useScreen && this._currentRenderTarget) {
  10187. return this._currentRenderTarget.width;
  10188. }
  10189. return this._gl.drawingBufferWidth;
  10190. };
  10191. Engine.prototype.getRenderHeight = function (useScreen) {
  10192. if (useScreen === void 0) { useScreen = false; }
  10193. if (!useScreen && this._currentRenderTarget) {
  10194. return this._currentRenderTarget.height;
  10195. }
  10196. return this._gl.drawingBufferHeight;
  10197. };
  10198. Engine.prototype.getRenderingCanvas = function () {
  10199. return this._renderingCanvas;
  10200. };
  10201. Engine.prototype.getRenderingCanvasClientRect = function () {
  10202. if (!this._renderingCanvas) {
  10203. return null;
  10204. }
  10205. return this._renderingCanvas.getBoundingClientRect();
  10206. };
  10207. Engine.prototype.setHardwareScalingLevel = function (level) {
  10208. this._hardwareScalingLevel = level;
  10209. this.resize();
  10210. };
  10211. Engine.prototype.getHardwareScalingLevel = function () {
  10212. return this._hardwareScalingLevel;
  10213. };
  10214. Engine.prototype.getLoadedTexturesCache = function () {
  10215. return this._internalTexturesCache;
  10216. };
  10217. Engine.prototype.getCaps = function () {
  10218. return this._caps;
  10219. };
  10220. Object.defineProperty(Engine.prototype, "drawCalls", {
  10221. /** The number of draw calls submitted last frame */
  10222. get: function () {
  10223. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10224. return 0;
  10225. },
  10226. enumerable: true,
  10227. configurable: true
  10228. });
  10229. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10230. get: function () {
  10231. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10232. return null;
  10233. },
  10234. enumerable: true,
  10235. configurable: true
  10236. });
  10237. Engine.prototype.getDepthFunction = function () {
  10238. return this._depthCullingState.depthFunc;
  10239. };
  10240. Engine.prototype.setDepthFunction = function (depthFunc) {
  10241. this._depthCullingState.depthFunc = depthFunc;
  10242. };
  10243. Engine.prototype.setDepthFunctionToGreater = function () {
  10244. this._depthCullingState.depthFunc = this._gl.GREATER;
  10245. };
  10246. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10247. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10248. };
  10249. Engine.prototype.setDepthFunctionToLess = function () {
  10250. this._depthCullingState.depthFunc = this._gl.LESS;
  10251. };
  10252. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10253. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10254. };
  10255. Engine.prototype.getStencilBuffer = function () {
  10256. return this._stencilState.stencilTest;
  10257. };
  10258. Engine.prototype.setStencilBuffer = function (enable) {
  10259. this._stencilState.stencilTest = enable;
  10260. };
  10261. Engine.prototype.getStencilMask = function () {
  10262. return this._stencilState.stencilMask;
  10263. };
  10264. Engine.prototype.setStencilMask = function (mask) {
  10265. this._stencilState.stencilMask = mask;
  10266. };
  10267. Engine.prototype.getStencilFunction = function () {
  10268. return this._stencilState.stencilFunc;
  10269. };
  10270. Engine.prototype.getStencilFunctionReference = function () {
  10271. return this._stencilState.stencilFuncRef;
  10272. };
  10273. Engine.prototype.getStencilFunctionMask = function () {
  10274. return this._stencilState.stencilFuncMask;
  10275. };
  10276. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10277. this._stencilState.stencilFunc = stencilFunc;
  10278. };
  10279. Engine.prototype.setStencilFunctionReference = function (reference) {
  10280. this._stencilState.stencilFuncRef = reference;
  10281. };
  10282. Engine.prototype.setStencilFunctionMask = function (mask) {
  10283. this._stencilState.stencilFuncMask = mask;
  10284. };
  10285. Engine.prototype.getStencilOperationFail = function () {
  10286. return this._stencilState.stencilOpStencilFail;
  10287. };
  10288. Engine.prototype.getStencilOperationDepthFail = function () {
  10289. return this._stencilState.stencilOpDepthFail;
  10290. };
  10291. Engine.prototype.getStencilOperationPass = function () {
  10292. return this._stencilState.stencilOpStencilDepthPass;
  10293. };
  10294. Engine.prototype.setStencilOperationFail = function (operation) {
  10295. this._stencilState.stencilOpStencilFail = operation;
  10296. };
  10297. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10298. this._stencilState.stencilOpDepthFail = operation;
  10299. };
  10300. Engine.prototype.setStencilOperationPass = function (operation) {
  10301. this._stencilState.stencilOpStencilDepthPass = operation;
  10302. };
  10303. Engine.prototype.setDitheringState = function (value) {
  10304. if (value) {
  10305. this._gl.enable(this._gl.DITHER);
  10306. }
  10307. else {
  10308. this._gl.disable(this._gl.DITHER);
  10309. }
  10310. };
  10311. Engine.prototype.setRasterizerState = function (value) {
  10312. if (value) {
  10313. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10314. }
  10315. else {
  10316. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10317. }
  10318. };
  10319. /**
  10320. * stop executing a render loop function and remove it from the execution array
  10321. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10322. */
  10323. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10324. if (!renderFunction) {
  10325. this._activeRenderLoops = [];
  10326. return;
  10327. }
  10328. var index = this._activeRenderLoops.indexOf(renderFunction);
  10329. if (index >= 0) {
  10330. this._activeRenderLoops.splice(index, 1);
  10331. }
  10332. };
  10333. Engine.prototype._renderLoop = function () {
  10334. if (!this._contextWasLost) {
  10335. var shouldRender = true;
  10336. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10337. shouldRender = false;
  10338. }
  10339. if (shouldRender) {
  10340. // Start new frame
  10341. this.beginFrame();
  10342. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10343. var renderFunction = this._activeRenderLoops[index];
  10344. renderFunction();
  10345. }
  10346. // Present
  10347. this.endFrame();
  10348. }
  10349. }
  10350. if (this._activeRenderLoops.length > 0) {
  10351. // Register new frame
  10352. var requester = null;
  10353. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10354. requester = this._vrDisplay;
  10355. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10356. }
  10357. else {
  10358. this._renderingQueueLaunched = false;
  10359. }
  10360. };
  10361. /**
  10362. * Register and execute a render loop. The engine can have more than one render function.
  10363. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10364. * @example
  10365. * engine.runRenderLoop(function () {
  10366. * scene.render()
  10367. * })
  10368. */
  10369. Engine.prototype.runRenderLoop = function (renderFunction) {
  10370. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10371. return;
  10372. }
  10373. this._activeRenderLoops.push(renderFunction);
  10374. if (!this._renderingQueueLaunched) {
  10375. this._renderingQueueLaunched = true;
  10376. this._bindedRenderFunction = this._renderLoop.bind(this);
  10377. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10378. }
  10379. };
  10380. /**
  10381. * Toggle full screen mode.
  10382. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10383. * @param {any} options - an options object to be sent to the requestFullscreen function
  10384. */
  10385. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10386. if (this.isFullscreen) {
  10387. BABYLON.Tools.ExitFullscreen();
  10388. }
  10389. else {
  10390. this._pointerLockRequested = requestPointerLock;
  10391. if (this._renderingCanvas) {
  10392. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10393. }
  10394. }
  10395. };
  10396. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10397. if (stencil === void 0) { stencil = false; }
  10398. this.applyStates();
  10399. var mode = 0;
  10400. if (backBuffer && color) {
  10401. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10402. mode |= this._gl.COLOR_BUFFER_BIT;
  10403. }
  10404. if (depth) {
  10405. this._gl.clearDepth(1.0);
  10406. mode |= this._gl.DEPTH_BUFFER_BIT;
  10407. }
  10408. if (stencil) {
  10409. this._gl.clearStencil(0);
  10410. mode |= this._gl.STENCIL_BUFFER_BIT;
  10411. }
  10412. this._gl.clear(mode);
  10413. };
  10414. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10415. var gl = this._gl;
  10416. // Save state
  10417. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10418. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10419. // Change state
  10420. gl.enable(gl.SCISSOR_TEST);
  10421. gl.scissor(x, y, width, height);
  10422. // Clear
  10423. this.clear(clearColor, true, true, true);
  10424. // Restore state
  10425. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10426. if (curScissor === true) {
  10427. gl.enable(gl.SCISSOR_TEST);
  10428. }
  10429. else {
  10430. gl.disable(gl.SCISSOR_TEST);
  10431. }
  10432. };
  10433. /**
  10434. * Set the WebGL's viewport
  10435. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10436. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10437. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10438. */
  10439. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10440. var width = requiredWidth || this.getRenderWidth();
  10441. var height = requiredHeight || this.getRenderHeight();
  10442. var x = viewport.x || 0;
  10443. var y = viewport.y || 0;
  10444. this._cachedViewport = viewport;
  10445. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10446. };
  10447. /**
  10448. * Directly set the WebGL Viewport
  10449. * The x, y, width & height are directly passed to the WebGL call
  10450. * @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.
  10451. */
  10452. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10453. var currentViewport = this._cachedViewport;
  10454. this._cachedViewport = null;
  10455. this._gl.viewport(x, y, width, height);
  10456. return currentViewport;
  10457. };
  10458. Engine.prototype.beginFrame = function () {
  10459. this.onBeginFrameObservable.notifyObservers(this);
  10460. this._measureFps();
  10461. };
  10462. Engine.prototype.endFrame = function () {
  10463. //force a flush in case we are using a bad OS.
  10464. if (this._badOS) {
  10465. this.flushFramebuffer();
  10466. }
  10467. //submit frame to the vr device, if enabled
  10468. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10469. // TODO: We should only submit the frame if we read frameData successfully.
  10470. this._vrDisplay.submitFrame();
  10471. }
  10472. this.onEndFrameObservable.notifyObservers(this);
  10473. };
  10474. /**
  10475. * resize the view according to the canvas' size.
  10476. * @example
  10477. * window.addEventListener("resize", function () {
  10478. * engine.resize();
  10479. * });
  10480. */
  10481. Engine.prototype.resize = function () {
  10482. // We're not resizing the size of the canvas while in VR mode & presenting
  10483. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10484. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10485. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10486. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10487. }
  10488. };
  10489. /**
  10490. * force a specific size of the canvas
  10491. * @param {number} width - the new canvas' width
  10492. * @param {number} height - the new canvas' height
  10493. */
  10494. Engine.prototype.setSize = function (width, height) {
  10495. if (!this._renderingCanvas) {
  10496. return;
  10497. }
  10498. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10499. return;
  10500. }
  10501. this._renderingCanvas.width = width;
  10502. this._renderingCanvas.height = height;
  10503. for (var index = 0; index < this.scenes.length; index++) {
  10504. var scene = this.scenes[index];
  10505. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10506. var cam = scene.cameras[camIndex];
  10507. cam._currentRenderId = 0;
  10508. }
  10509. }
  10510. if (this.onResizeObservable.hasObservers) {
  10511. this.onResizeObservable.notifyObservers(this);
  10512. }
  10513. };
  10514. // WebVR functions
  10515. Engine.prototype.isVRDevicePresent = function () {
  10516. return !!this._vrDisplay;
  10517. };
  10518. Engine.prototype.getVRDevice = function () {
  10519. return this._vrDisplay;
  10520. };
  10521. Engine.prototype.initWebVR = function () {
  10522. var _this = this;
  10523. var notifyObservers = function () {
  10524. var eventArgs = {
  10525. vrDisplay: _this._vrDisplay,
  10526. vrSupported: _this._vrSupported
  10527. };
  10528. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10529. };
  10530. if (!this._onVrDisplayConnect) {
  10531. this._onVrDisplayConnect = function (event) {
  10532. _this._vrDisplay = event.display;
  10533. notifyObservers();
  10534. };
  10535. this._onVrDisplayDisconnect = function () {
  10536. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10537. _this._vrDisplay = undefined;
  10538. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10539. notifyObservers();
  10540. };
  10541. this._onVrDisplayPresentChange = function () {
  10542. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10543. };
  10544. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10545. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10546. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10547. }
  10548. this._getVRDisplays(notifyObservers);
  10549. return this.onVRDisplayChangedObservable;
  10550. };
  10551. Engine.prototype.enableVR = function () {
  10552. var _this = this;
  10553. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10554. var onResolved = function () {
  10555. _this.onVRRequestPresentComplete.notifyObservers(true);
  10556. _this._onVRFullScreenTriggered();
  10557. };
  10558. var onRejected = function () {
  10559. _this.onVRRequestPresentComplete.notifyObservers(false);
  10560. };
  10561. this.onVRRequestPresentStart.notifyObservers(this);
  10562. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10563. }
  10564. };
  10565. Engine.prototype.disableVR = function () {
  10566. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10567. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10568. }
  10569. };
  10570. Engine.prototype._getVRDisplays = function (callback) {
  10571. var _this = this;
  10572. var getWebVRDevices = function (devices) {
  10573. _this._vrSupported = true;
  10574. // note that devices may actually be an empty array. This is fine;
  10575. // we expect this._vrDisplay to be undefined in this case.
  10576. return _this._vrDisplay = devices[0];
  10577. };
  10578. if (navigator.getVRDisplays) {
  10579. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10580. // TODO: System CANNOT support WebVR, despite API presence.
  10581. _this._vrSupported = false;
  10582. callback();
  10583. });
  10584. }
  10585. else {
  10586. // TODO: Browser does not support WebVR
  10587. this._vrDisplay = undefined;
  10588. this._vrSupported = false;
  10589. callback();
  10590. }
  10591. };
  10592. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10593. if (this._currentRenderTarget) {
  10594. this.unBindFramebuffer(this._currentRenderTarget);
  10595. }
  10596. this._currentRenderTarget = texture;
  10597. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10598. var gl = this._gl;
  10599. if (texture.isCube) {
  10600. if (faceIndex === undefined) {
  10601. faceIndex = 0;
  10602. }
  10603. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10604. }
  10605. if (this._cachedViewport && !forceFullscreenViewport) {
  10606. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10607. }
  10608. else {
  10609. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10610. }
  10611. this.wipeCaches();
  10612. };
  10613. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10614. if (this._currentFramebuffer !== framebuffer) {
  10615. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10616. this._currentFramebuffer = framebuffer;
  10617. }
  10618. };
  10619. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10620. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10621. this._currentRenderTarget = null;
  10622. // If MSAA, we need to bitblt back to main texture
  10623. var gl = this._gl;
  10624. if (texture._MSAAFramebuffer) {
  10625. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10626. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10627. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10628. }
  10629. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10630. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10631. gl.generateMipmap(gl.TEXTURE_2D);
  10632. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10633. }
  10634. if (onBeforeUnbind) {
  10635. if (texture._MSAAFramebuffer) {
  10636. // Bind the correct framebuffer
  10637. this.bindUnboundFramebuffer(texture._framebuffer);
  10638. }
  10639. onBeforeUnbind();
  10640. }
  10641. this.bindUnboundFramebuffer(null);
  10642. };
  10643. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10644. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10645. this._currentRenderTarget = null;
  10646. // If MSAA, we need to bitblt back to main texture
  10647. var gl = this._gl;
  10648. if (textures[0]._MSAAFramebuffer) {
  10649. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10650. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10651. var attachments = textures[0]._attachments;
  10652. if (!attachments) {
  10653. attachments = new Array(textures.length);
  10654. textures[0]._attachments = attachments;
  10655. }
  10656. for (var i = 0; i < textures.length; i++) {
  10657. var texture = textures[i];
  10658. for (var j = 0; j < attachments.length; j++) {
  10659. attachments[j] = gl.NONE;
  10660. }
  10661. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10662. gl.readBuffer(attachments[i]);
  10663. gl.drawBuffers(attachments);
  10664. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10665. }
  10666. for (var i = 0; i < attachments.length; i++) {
  10667. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10668. }
  10669. gl.drawBuffers(attachments);
  10670. }
  10671. for (var i = 0; i < textures.length; i++) {
  10672. var texture = textures[i];
  10673. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10674. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10675. gl.generateMipmap(gl.TEXTURE_2D);
  10676. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10677. }
  10678. }
  10679. if (onBeforeUnbind) {
  10680. if (textures[0]._MSAAFramebuffer) {
  10681. // Bind the correct framebuffer
  10682. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10683. }
  10684. onBeforeUnbind();
  10685. }
  10686. this.bindUnboundFramebuffer(null);
  10687. };
  10688. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10689. if (texture.generateMipMaps) {
  10690. var gl = this._gl;
  10691. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10692. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10693. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10694. }
  10695. };
  10696. Engine.prototype.flushFramebuffer = function () {
  10697. this._gl.flush();
  10698. };
  10699. Engine.prototype.restoreDefaultFramebuffer = function () {
  10700. if (this._currentRenderTarget) {
  10701. this.unBindFramebuffer(this._currentRenderTarget);
  10702. }
  10703. else {
  10704. this.bindUnboundFramebuffer(null);
  10705. }
  10706. if (this._cachedViewport) {
  10707. this.setViewport(this._cachedViewport);
  10708. }
  10709. this.wipeCaches();
  10710. };
  10711. // UBOs
  10712. Engine.prototype.createUniformBuffer = function (elements) {
  10713. var ubo = this._gl.createBuffer();
  10714. if (!ubo) {
  10715. throw new Error("Unable to create uniform buffer");
  10716. }
  10717. this.bindUniformBuffer(ubo);
  10718. if (elements instanceof Float32Array) {
  10719. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10720. }
  10721. else {
  10722. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10723. }
  10724. this.bindUniformBuffer(null);
  10725. ubo.references = 1;
  10726. return ubo;
  10727. };
  10728. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10729. var ubo = this._gl.createBuffer();
  10730. if (!ubo) {
  10731. throw new Error("Unable to create dynamic uniform buffer");
  10732. }
  10733. this.bindUniformBuffer(ubo);
  10734. if (elements instanceof Float32Array) {
  10735. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10736. }
  10737. else {
  10738. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10739. }
  10740. this.bindUniformBuffer(null);
  10741. ubo.references = 1;
  10742. return ubo;
  10743. };
  10744. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10745. this.bindUniformBuffer(uniformBuffer);
  10746. if (offset === undefined) {
  10747. offset = 0;
  10748. }
  10749. if (count === undefined) {
  10750. if (elements instanceof Float32Array) {
  10751. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10752. }
  10753. else {
  10754. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10755. }
  10756. }
  10757. else {
  10758. if (elements instanceof Float32Array) {
  10759. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10760. }
  10761. else {
  10762. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10763. }
  10764. }
  10765. this.bindUniformBuffer(null);
  10766. };
  10767. // VBOs
  10768. Engine.prototype._resetVertexBufferBinding = function () {
  10769. this.bindArrayBuffer(null);
  10770. this._cachedVertexBuffers = null;
  10771. };
  10772. Engine.prototype.createVertexBuffer = function (vertices) {
  10773. var vbo = this._gl.createBuffer();
  10774. if (!vbo) {
  10775. throw new Error("Unable to create vertex buffer");
  10776. }
  10777. this.bindArrayBuffer(vbo);
  10778. if (vertices instanceof Float32Array) {
  10779. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10780. }
  10781. else {
  10782. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10783. }
  10784. this._resetVertexBufferBinding();
  10785. vbo.references = 1;
  10786. return vbo;
  10787. };
  10788. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10789. var vbo = this._gl.createBuffer();
  10790. if (!vbo) {
  10791. throw new Error("Unable to create dynamic vertex buffer");
  10792. }
  10793. this.bindArrayBuffer(vbo);
  10794. if (vertices instanceof Float32Array) {
  10795. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10796. }
  10797. else {
  10798. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10799. }
  10800. this._resetVertexBufferBinding();
  10801. vbo.references = 1;
  10802. return vbo;
  10803. };
  10804. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10805. if (offset === void 0) { offset = 0; }
  10806. // Force cache update
  10807. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10808. this.bindIndexBuffer(indexBuffer);
  10809. var arrayBuffer;
  10810. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10811. arrayBuffer = indices;
  10812. }
  10813. else {
  10814. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10815. }
  10816. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10817. this._resetIndexBufferBinding();
  10818. };
  10819. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10820. this.bindArrayBuffer(vertexBuffer);
  10821. if (offset === undefined) {
  10822. offset = 0;
  10823. }
  10824. if (count === undefined) {
  10825. if (vertices instanceof Float32Array) {
  10826. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10827. }
  10828. else {
  10829. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10830. }
  10831. }
  10832. else {
  10833. if (vertices instanceof Float32Array) {
  10834. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10835. }
  10836. else {
  10837. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10838. }
  10839. }
  10840. this._resetVertexBufferBinding();
  10841. };
  10842. Engine.prototype._resetIndexBufferBinding = function () {
  10843. this.bindIndexBuffer(null);
  10844. this._cachedIndexBuffer = null;
  10845. };
  10846. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10847. var vbo = this._gl.createBuffer();
  10848. if (!vbo) {
  10849. throw new Error("Unable to create index buffer");
  10850. }
  10851. this.bindIndexBuffer(vbo);
  10852. // Check for 32 bits indices
  10853. var arrayBuffer;
  10854. var need32Bits = false;
  10855. if (indices instanceof Uint16Array) {
  10856. arrayBuffer = indices;
  10857. }
  10858. else {
  10859. //check 32 bit support
  10860. if (this._caps.uintIndices) {
  10861. if (indices instanceof Uint32Array) {
  10862. arrayBuffer = indices;
  10863. need32Bits = true;
  10864. }
  10865. else {
  10866. //number[] or Int32Array, check if 32 bit is necessary
  10867. for (var index = 0; index < indices.length; index++) {
  10868. if (indices[index] > 65535) {
  10869. need32Bits = true;
  10870. break;
  10871. }
  10872. }
  10873. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10874. }
  10875. }
  10876. else {
  10877. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10878. arrayBuffer = new Uint16Array(indices);
  10879. }
  10880. }
  10881. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10882. this._resetIndexBufferBinding();
  10883. vbo.references = 1;
  10884. vbo.is32Bits = need32Bits;
  10885. return vbo;
  10886. };
  10887. Engine.prototype.bindArrayBuffer = function (buffer) {
  10888. if (!this._vaoRecordInProgress) {
  10889. this._unbindVertexArrayObject();
  10890. }
  10891. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10892. };
  10893. Engine.prototype.bindUniformBuffer = function (buffer) {
  10894. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10895. };
  10896. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10897. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10898. };
  10899. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10900. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10901. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10902. };
  10903. ;
  10904. Engine.prototype.bindIndexBuffer = function (buffer) {
  10905. if (!this._vaoRecordInProgress) {
  10906. this._unbindVertexArrayObject();
  10907. }
  10908. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10909. };
  10910. Engine.prototype.bindBuffer = function (buffer, target) {
  10911. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10912. this._gl.bindBuffer(target, buffer);
  10913. this._currentBoundBuffer[target] = buffer;
  10914. }
  10915. };
  10916. Engine.prototype.updateArrayBuffer = function (data) {
  10917. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10918. };
  10919. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10920. var pointer = this._currentBufferPointers[indx];
  10921. var changed = false;
  10922. if (!pointer.active) {
  10923. changed = true;
  10924. pointer.active = true;
  10925. pointer.index = indx;
  10926. pointer.size = size;
  10927. pointer.type = type;
  10928. pointer.normalized = normalized;
  10929. pointer.stride = stride;
  10930. pointer.offset = offset;
  10931. pointer.buffer = buffer;
  10932. }
  10933. else {
  10934. if (pointer.buffer !== buffer) {
  10935. pointer.buffer = buffer;
  10936. changed = true;
  10937. }
  10938. if (pointer.size !== size) {
  10939. pointer.size = size;
  10940. changed = true;
  10941. }
  10942. if (pointer.type !== type) {
  10943. pointer.type = type;
  10944. changed = true;
  10945. }
  10946. if (pointer.normalized !== normalized) {
  10947. pointer.normalized = normalized;
  10948. changed = true;
  10949. }
  10950. if (pointer.stride !== stride) {
  10951. pointer.stride = stride;
  10952. changed = true;
  10953. }
  10954. if (pointer.offset !== offset) {
  10955. pointer.offset = offset;
  10956. changed = true;
  10957. }
  10958. }
  10959. if (changed || this._vaoRecordInProgress) {
  10960. this.bindArrayBuffer(buffer);
  10961. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10962. }
  10963. };
  10964. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10965. if (indexBuffer == null) {
  10966. return;
  10967. }
  10968. if (this._cachedIndexBuffer !== indexBuffer) {
  10969. this._cachedIndexBuffer = indexBuffer;
  10970. this.bindIndexBuffer(indexBuffer);
  10971. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10972. }
  10973. };
  10974. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10975. var attributes = effect.getAttributesNames();
  10976. if (!this._vaoRecordInProgress) {
  10977. this._unbindVertexArrayObject();
  10978. }
  10979. this.unbindAllAttributes();
  10980. for (var index = 0; index < attributes.length; index++) {
  10981. var order = effect.getAttributeLocation(index);
  10982. if (order >= 0) {
  10983. var vertexBuffer = vertexBuffers[attributes[index]];
  10984. if (!vertexBuffer) {
  10985. continue;
  10986. }
  10987. this._gl.enableVertexAttribArray(order);
  10988. if (!this._vaoRecordInProgress) {
  10989. this._vertexAttribArraysEnabled[order] = true;
  10990. }
  10991. var buffer = vertexBuffer.getBuffer();
  10992. if (buffer) {
  10993. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10994. if (vertexBuffer.getIsInstanced()) {
  10995. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10996. if (!this._vaoRecordInProgress) {
  10997. this._currentInstanceLocations.push(order);
  10998. this._currentInstanceBuffers.push(buffer);
  10999. }
  11000. }
  11001. }
  11002. }
  11003. }
  11004. };
  11005. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11006. var vao = this._gl.createVertexArray();
  11007. this._vaoRecordInProgress = true;
  11008. this._gl.bindVertexArray(vao);
  11009. this._mustWipeVertexAttributes = true;
  11010. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11011. this.bindIndexBuffer(indexBuffer);
  11012. this._vaoRecordInProgress = false;
  11013. this._gl.bindVertexArray(null);
  11014. return vao;
  11015. };
  11016. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11017. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11018. this._cachedVertexArrayObject = vertexArrayObject;
  11019. this._gl.bindVertexArray(vertexArrayObject);
  11020. this._cachedVertexBuffers = null;
  11021. this._cachedIndexBuffer = null;
  11022. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11023. this._mustWipeVertexAttributes = true;
  11024. }
  11025. };
  11026. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11027. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11028. this._cachedVertexBuffers = vertexBuffer;
  11029. this._cachedEffectForVertexBuffers = effect;
  11030. var attributesCount = effect.getAttributesCount();
  11031. this._unbindVertexArrayObject();
  11032. this.unbindAllAttributes();
  11033. var offset = 0;
  11034. for (var index = 0; index < attributesCount; index++) {
  11035. if (index < vertexDeclaration.length) {
  11036. var order = effect.getAttributeLocation(index);
  11037. if (order >= 0) {
  11038. this._gl.enableVertexAttribArray(order);
  11039. this._vertexAttribArraysEnabled[order] = true;
  11040. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11041. }
  11042. offset += vertexDeclaration[index] * 4;
  11043. }
  11044. }
  11045. }
  11046. this._bindIndexBufferWithCache(indexBuffer);
  11047. };
  11048. Engine.prototype._unbindVertexArrayObject = function () {
  11049. if (!this._cachedVertexArrayObject) {
  11050. return;
  11051. }
  11052. this._cachedVertexArrayObject = null;
  11053. this._gl.bindVertexArray(null);
  11054. };
  11055. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11056. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11057. this._cachedVertexBuffers = vertexBuffers;
  11058. this._cachedEffectForVertexBuffers = effect;
  11059. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11060. }
  11061. this._bindIndexBufferWithCache(indexBuffer);
  11062. };
  11063. Engine.prototype.unbindInstanceAttributes = function () {
  11064. var boundBuffer;
  11065. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11066. var instancesBuffer = this._currentInstanceBuffers[i];
  11067. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11068. boundBuffer = instancesBuffer;
  11069. this.bindArrayBuffer(instancesBuffer);
  11070. }
  11071. var offsetLocation = this._currentInstanceLocations[i];
  11072. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11073. }
  11074. this._currentInstanceBuffers.length = 0;
  11075. this._currentInstanceLocations.length = 0;
  11076. };
  11077. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11078. this._gl.deleteVertexArray(vao);
  11079. };
  11080. Engine.prototype._releaseBuffer = function (buffer) {
  11081. buffer.references--;
  11082. if (buffer.references === 0) {
  11083. this._gl.deleteBuffer(buffer);
  11084. return true;
  11085. }
  11086. return false;
  11087. };
  11088. Engine.prototype.createInstancesBuffer = function (capacity) {
  11089. var buffer = this._gl.createBuffer();
  11090. if (!buffer) {
  11091. throw new Error("Unable to create instance buffer");
  11092. }
  11093. buffer.capacity = capacity;
  11094. this.bindArrayBuffer(buffer);
  11095. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11096. return buffer;
  11097. };
  11098. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11099. this._gl.deleteBuffer(buffer);
  11100. };
  11101. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11102. this.bindArrayBuffer(instancesBuffer);
  11103. if (data) {
  11104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11105. }
  11106. if (offsetLocations[0].index !== undefined) {
  11107. var stride = 0;
  11108. for (var i = 0; i < offsetLocations.length; i++) {
  11109. var ai = offsetLocations[i];
  11110. stride += ai.attributeSize * 4;
  11111. }
  11112. for (var i = 0; i < offsetLocations.length; i++) {
  11113. var ai = offsetLocations[i];
  11114. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11115. this._gl.enableVertexAttribArray(ai.index);
  11116. this._vertexAttribArraysEnabled[ai.index] = true;
  11117. }
  11118. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11119. this._gl.vertexAttribDivisor(ai.index, 1);
  11120. this._currentInstanceLocations.push(ai.index);
  11121. this._currentInstanceBuffers.push(instancesBuffer);
  11122. }
  11123. }
  11124. else {
  11125. for (var index = 0; index < 4; index++) {
  11126. var offsetLocation = offsetLocations[index];
  11127. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11128. this._gl.enableVertexAttribArray(offsetLocation);
  11129. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11130. }
  11131. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11132. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11133. this._currentInstanceLocations.push(offsetLocation);
  11134. this._currentInstanceBuffers.push(instancesBuffer);
  11135. }
  11136. }
  11137. };
  11138. Engine.prototype.applyStates = function () {
  11139. this._depthCullingState.apply(this._gl);
  11140. this._stencilState.apply(this._gl);
  11141. this._alphaState.apply(this._gl);
  11142. };
  11143. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11144. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11145. };
  11146. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11147. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11148. };
  11149. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11150. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11151. };
  11152. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11153. // Apply states
  11154. this.applyStates();
  11155. this._drawCalls.addCount(1, false);
  11156. // Render
  11157. var drawMode = this.DrawMode(fillMode);
  11158. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11159. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11160. if (instancesCount) {
  11161. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11162. }
  11163. else {
  11164. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11165. }
  11166. };
  11167. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11168. // Apply states
  11169. this.applyStates();
  11170. this._drawCalls.addCount(1, false);
  11171. var drawMode = this.DrawMode(fillMode);
  11172. if (instancesCount) {
  11173. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11174. }
  11175. else {
  11176. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11177. }
  11178. };
  11179. Engine.prototype.DrawMode = function (fillMode) {
  11180. switch (fillMode) {
  11181. // Triangle views
  11182. case BABYLON.Material.TriangleFillMode:
  11183. return this._gl.TRIANGLES;
  11184. case BABYLON.Material.PointFillMode:
  11185. return this._gl.POINTS;
  11186. case BABYLON.Material.WireFrameFillMode:
  11187. return this._gl.LINES;
  11188. // Draw modes
  11189. case BABYLON.Material.PointListDrawMode:
  11190. return this._gl.POINTS;
  11191. case BABYLON.Material.LineListDrawMode:
  11192. return this._gl.LINES;
  11193. case BABYLON.Material.LineLoopDrawMode:
  11194. return this._gl.LINE_LOOP;
  11195. case BABYLON.Material.LineStripDrawMode:
  11196. return this._gl.LINE_STRIP;
  11197. case BABYLON.Material.TriangleStripDrawMode:
  11198. return this._gl.TRIANGLE_STRIP;
  11199. case BABYLON.Material.TriangleFanDrawMode:
  11200. return this._gl.TRIANGLE_FAN;
  11201. default:
  11202. return this._gl.TRIANGLES;
  11203. }
  11204. };
  11205. // Shaders
  11206. Engine.prototype._releaseEffect = function (effect) {
  11207. if (this._compiledEffects[effect._key]) {
  11208. delete this._compiledEffects[effect._key];
  11209. this._deleteProgram(effect.getProgram());
  11210. }
  11211. };
  11212. Engine.prototype._deleteProgram = function (program) {
  11213. if (program) {
  11214. program.__SPECTOR_rebuildProgram = null;
  11215. if (program.transformFeedback) {
  11216. this.deleteTransformFeedback(program.transformFeedback);
  11217. program.transformFeedback = null;
  11218. }
  11219. this._gl.deleteProgram(program);
  11220. }
  11221. };
  11222. /**
  11223. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11224. * @param samplers An array of string used to represent textures
  11225. */
  11226. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11227. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11228. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11229. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11230. if (this._compiledEffects[name]) {
  11231. var compiledEffect = this._compiledEffects[name];
  11232. if (onCompiled && compiledEffect.isReady()) {
  11233. onCompiled(compiledEffect);
  11234. }
  11235. return compiledEffect;
  11236. }
  11237. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11238. effect._key = name;
  11239. this._compiledEffects[name] = effect;
  11240. return effect;
  11241. };
  11242. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11243. if (uniformsNames === void 0) { uniformsNames = []; }
  11244. if (samplers === void 0) { samplers = []; }
  11245. if (defines === void 0) { defines = ""; }
  11246. return this.createEffect({
  11247. vertex: "particles",
  11248. fragmentElement: fragmentName
  11249. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11250. };
  11251. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11252. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11253. context = context || this._gl;
  11254. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11255. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11256. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11257. };
  11258. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11259. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11260. context = context || this._gl;
  11261. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11262. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11263. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11264. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11265. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11266. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11267. return program;
  11268. };
  11269. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11270. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11271. var shaderProgram = context.createProgram();
  11272. if (!shaderProgram) {
  11273. throw new Error("Unable to create program");
  11274. }
  11275. context.attachShader(shaderProgram, vertexShader);
  11276. context.attachShader(shaderProgram, fragmentShader);
  11277. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11278. var transformFeedback = this.createTransformFeedback();
  11279. this.bindTransformFeedback(transformFeedback);
  11280. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11281. shaderProgram.transformFeedback = transformFeedback;
  11282. }
  11283. context.linkProgram(shaderProgram);
  11284. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11285. this.bindTransformFeedback(null);
  11286. }
  11287. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11288. if (!linked) {
  11289. context.validateProgram(shaderProgram);
  11290. var error = context.getProgramInfoLog(shaderProgram);
  11291. if (error) {
  11292. throw new Error(error);
  11293. }
  11294. }
  11295. context.deleteShader(vertexShader);
  11296. context.deleteShader(fragmentShader);
  11297. return shaderProgram;
  11298. };
  11299. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11300. var results = new Array();
  11301. for (var index = 0; index < uniformsNames.length; index++) {
  11302. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11303. }
  11304. return results;
  11305. };
  11306. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11307. var results = [];
  11308. for (var index = 0; index < attributesNames.length; index++) {
  11309. try {
  11310. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11311. }
  11312. catch (e) {
  11313. results.push(-1);
  11314. }
  11315. }
  11316. return results;
  11317. };
  11318. Engine.prototype.enableEffect = function (effect) {
  11319. if (!effect) {
  11320. return;
  11321. }
  11322. // Use program
  11323. this.bindSamplers(effect);
  11324. this._currentEffect = effect;
  11325. if (effect.onBind) {
  11326. effect.onBind(effect);
  11327. }
  11328. effect.onBindObservable.notifyObservers(effect);
  11329. };
  11330. Engine.prototype.setIntArray = function (uniform, array) {
  11331. if (!uniform)
  11332. return;
  11333. this._gl.uniform1iv(uniform, array);
  11334. };
  11335. Engine.prototype.setIntArray2 = function (uniform, array) {
  11336. if (!uniform || array.length % 2 !== 0)
  11337. return;
  11338. this._gl.uniform2iv(uniform, array);
  11339. };
  11340. Engine.prototype.setIntArray3 = function (uniform, array) {
  11341. if (!uniform || array.length % 3 !== 0)
  11342. return;
  11343. this._gl.uniform3iv(uniform, array);
  11344. };
  11345. Engine.prototype.setIntArray4 = function (uniform, array) {
  11346. if (!uniform || array.length % 4 !== 0)
  11347. return;
  11348. this._gl.uniform4iv(uniform, array);
  11349. };
  11350. Engine.prototype.setFloatArray = function (uniform, array) {
  11351. if (!uniform)
  11352. return;
  11353. this._gl.uniform1fv(uniform, array);
  11354. };
  11355. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11356. if (!uniform || array.length % 2 !== 0)
  11357. return;
  11358. this._gl.uniform2fv(uniform, array);
  11359. };
  11360. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11361. if (!uniform || array.length % 3 !== 0)
  11362. return;
  11363. this._gl.uniform3fv(uniform, array);
  11364. };
  11365. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11366. if (!uniform || array.length % 4 !== 0)
  11367. return;
  11368. this._gl.uniform4fv(uniform, array);
  11369. };
  11370. Engine.prototype.setArray = function (uniform, array) {
  11371. if (!uniform)
  11372. return;
  11373. this._gl.uniform1fv(uniform, array);
  11374. };
  11375. Engine.prototype.setArray2 = function (uniform, array) {
  11376. if (!uniform || array.length % 2 !== 0)
  11377. return;
  11378. this._gl.uniform2fv(uniform, array);
  11379. };
  11380. Engine.prototype.setArray3 = function (uniform, array) {
  11381. if (!uniform || array.length % 3 !== 0)
  11382. return;
  11383. this._gl.uniform3fv(uniform, array);
  11384. };
  11385. Engine.prototype.setArray4 = function (uniform, array) {
  11386. if (!uniform || array.length % 4 !== 0)
  11387. return;
  11388. this._gl.uniform4fv(uniform, array);
  11389. };
  11390. Engine.prototype.setMatrices = function (uniform, matrices) {
  11391. if (!uniform)
  11392. return;
  11393. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11394. };
  11395. Engine.prototype.setMatrix = function (uniform, matrix) {
  11396. if (!uniform)
  11397. return;
  11398. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11399. };
  11400. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11401. if (!uniform)
  11402. return;
  11403. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11404. };
  11405. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11406. if (!uniform)
  11407. return;
  11408. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11409. };
  11410. Engine.prototype.setInt = function (uniform, value) {
  11411. if (!uniform)
  11412. return;
  11413. this._gl.uniform1i(uniform, value);
  11414. };
  11415. Engine.prototype.setFloat = function (uniform, value) {
  11416. if (!uniform)
  11417. return;
  11418. this._gl.uniform1f(uniform, value);
  11419. };
  11420. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11421. if (!uniform)
  11422. return;
  11423. this._gl.uniform2f(uniform, x, y);
  11424. };
  11425. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11426. if (!uniform)
  11427. return;
  11428. this._gl.uniform3f(uniform, x, y, z);
  11429. };
  11430. Engine.prototype.setBool = function (uniform, bool) {
  11431. if (!uniform)
  11432. return;
  11433. this._gl.uniform1i(uniform, bool);
  11434. };
  11435. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11436. if (!uniform)
  11437. return;
  11438. this._gl.uniform4f(uniform, x, y, z, w);
  11439. };
  11440. Engine.prototype.setColor3 = function (uniform, color3) {
  11441. if (!uniform)
  11442. return;
  11443. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11444. };
  11445. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11446. if (!uniform)
  11447. return;
  11448. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11449. };
  11450. // States
  11451. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11452. if (zOffset === void 0) { zOffset = 0; }
  11453. if (reverseSide === void 0) { reverseSide = false; }
  11454. // Culling
  11455. if (this._depthCullingState.cull !== culling || force) {
  11456. this._depthCullingState.cull = culling;
  11457. }
  11458. // Cull face
  11459. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11460. if (this._depthCullingState.cullFace !== cullFace || force) {
  11461. this._depthCullingState.cullFace = cullFace;
  11462. }
  11463. // Z offset
  11464. this.setZOffset(zOffset);
  11465. // Front face
  11466. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11467. if (this._depthCullingState.frontFace !== frontFace || force) {
  11468. this._depthCullingState.frontFace = frontFace;
  11469. }
  11470. };
  11471. Engine.prototype.setZOffset = function (value) {
  11472. this._depthCullingState.zOffset = value;
  11473. };
  11474. Engine.prototype.getZOffset = function () {
  11475. return this._depthCullingState.zOffset;
  11476. };
  11477. Engine.prototype.setDepthBuffer = function (enable) {
  11478. this._depthCullingState.depthTest = enable;
  11479. };
  11480. Engine.prototype.getDepthWrite = function () {
  11481. return this._depthCullingState.depthMask;
  11482. };
  11483. Engine.prototype.setDepthWrite = function (enable) {
  11484. this._depthCullingState.depthMask = enable;
  11485. };
  11486. Engine.prototype.setColorWrite = function (enable) {
  11487. this._gl.colorMask(enable, enable, enable, enable);
  11488. this._colorWrite = enable;
  11489. };
  11490. Engine.prototype.getColorWrite = function () {
  11491. return this._colorWrite;
  11492. };
  11493. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11494. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11495. };
  11496. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11497. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11498. if (this._alphaMode === mode) {
  11499. return;
  11500. }
  11501. switch (mode) {
  11502. case Engine.ALPHA_DISABLE:
  11503. this._alphaState.alphaBlend = false;
  11504. break;
  11505. case Engine.ALPHA_PREMULTIPLIED:
  11506. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11507. this._alphaState.alphaBlend = true;
  11508. break;
  11509. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11510. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11511. this._alphaState.alphaBlend = true;
  11512. break;
  11513. case Engine.ALPHA_COMBINE:
  11514. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11515. this._alphaState.alphaBlend = true;
  11516. break;
  11517. case Engine.ALPHA_ONEONE:
  11518. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11519. this._alphaState.alphaBlend = true;
  11520. break;
  11521. case Engine.ALPHA_ADD:
  11522. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11523. this._alphaState.alphaBlend = true;
  11524. break;
  11525. case Engine.ALPHA_SUBTRACT:
  11526. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11527. this._alphaState.alphaBlend = true;
  11528. break;
  11529. case Engine.ALPHA_MULTIPLY:
  11530. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11531. this._alphaState.alphaBlend = true;
  11532. break;
  11533. case Engine.ALPHA_MAXIMIZED:
  11534. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11535. this._alphaState.alphaBlend = true;
  11536. break;
  11537. case Engine.ALPHA_INTERPOLATE:
  11538. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11539. this._alphaState.alphaBlend = true;
  11540. break;
  11541. case Engine.ALPHA_SCREENMODE:
  11542. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11543. this._alphaState.alphaBlend = true;
  11544. break;
  11545. }
  11546. if (!noDepthWriteChange) {
  11547. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11548. }
  11549. this._alphaMode = mode;
  11550. };
  11551. Engine.prototype.getAlphaMode = function () {
  11552. return this._alphaMode;
  11553. };
  11554. // Textures
  11555. Engine.prototype.wipeCaches = function (bruteForce) {
  11556. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11557. return;
  11558. }
  11559. this._currentEffect = null;
  11560. // 6/8/2017: deltakosh: Should not be required anymore.
  11561. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11562. if (bruteForce) {
  11563. this.resetTextureCache();
  11564. this._currentProgram = null;
  11565. this._stencilState.reset();
  11566. this._depthCullingState.reset();
  11567. this.setDepthFunctionToLessOrEqual();
  11568. this._alphaState.reset();
  11569. }
  11570. this._resetVertexBufferBinding();
  11571. this._cachedIndexBuffer = null;
  11572. this._cachedEffectForVertexBuffers = null;
  11573. this._unbindVertexArrayObject();
  11574. this.bindIndexBuffer(null);
  11575. };
  11576. /**
  11577. * Set the compressed texture format to use, based on the formats you have, and the formats
  11578. * supported by the hardware / browser.
  11579. *
  11580. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11581. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11582. * to API arguments needed to compressed textures. This puts the burden on the container
  11583. * generator to house the arcane code for determining these for current & future formats.
  11584. *
  11585. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11586. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11587. *
  11588. * Note: The result of this call is not taken into account when a texture is base64.
  11589. *
  11590. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11591. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11592. *
  11593. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11594. * @returns The extension selected.
  11595. */
  11596. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11597. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11598. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11599. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11600. return this._textureFormatInUse = this._texturesSupported[i];
  11601. }
  11602. }
  11603. }
  11604. // actively set format to nothing, to allow this to be called more than once
  11605. // and possibly fail the 2nd time
  11606. this._textureFormatInUse = null;
  11607. return null;
  11608. };
  11609. Engine.prototype._createTexture = function () {
  11610. var texture = this._gl.createTexture();
  11611. if (!texture) {
  11612. throw new Error("Unable to create texture");
  11613. }
  11614. return texture;
  11615. };
  11616. /**
  11617. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11618. * @param {string} urlArg- This contains one of the following:
  11619. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11620. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11621. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11622. *
  11623. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11624. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11625. * @param {Scene} scene- Needed for loading to the correct scene.
  11626. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11627. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11628. * @param {callback} onError- Optional callback to be called upon failure.
  11629. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11630. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11631. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11632. *
  11633. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11634. */
  11635. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11636. var _this = this;
  11637. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11638. if (onLoad === void 0) { onLoad = null; }
  11639. if (onError === void 0) { onError = null; }
  11640. if (buffer === void 0) { buffer = null; }
  11641. if (fallBack === void 0) { fallBack = null; }
  11642. if (format === void 0) { format = null; }
  11643. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11644. var fromData = url.substr(0, 5) === "data:";
  11645. var fromBlob = url.substr(0, 5) === "blob:";
  11646. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11647. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11648. // establish the file extension, if possible
  11649. var lastDot = url.lastIndexOf('.');
  11650. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11651. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11652. var isTGA = (extension === ".tga");
  11653. // determine if a ktx file should be substituted
  11654. var isKTX = false;
  11655. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11656. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11657. isKTX = true;
  11658. }
  11659. if (scene) {
  11660. scene._addPendingData(texture);
  11661. }
  11662. texture.url = url;
  11663. texture.generateMipMaps = !noMipmap;
  11664. texture.samplingMode = samplingMode;
  11665. texture.invertY = invertY;
  11666. if (!this._doNotHandleContextLost) {
  11667. // Keep a link to the buffer only if we plan to handle context lost
  11668. texture._buffer = buffer;
  11669. }
  11670. var onLoadObserver = null;
  11671. if (onLoad && !fallBack) {
  11672. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11673. }
  11674. if (!fallBack)
  11675. this._internalTexturesCache.push(texture);
  11676. var onerror = function (message, exception) {
  11677. if (scene) {
  11678. scene._removePendingData(texture);
  11679. }
  11680. if (onLoadObserver) {
  11681. texture.onLoadedObservable.remove(onLoadObserver);
  11682. }
  11683. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11684. if (isKTX) {
  11685. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11686. }
  11687. else if (BABYLON.Tools.UseFallbackTexture) {
  11688. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11689. }
  11690. if (onError) {
  11691. onError(message || "Unknown error", exception);
  11692. }
  11693. };
  11694. var callback = null;
  11695. // processing for non-image formats
  11696. if (isKTX || isTGA || isDDS) {
  11697. if (isKTX) {
  11698. callback = function (data) {
  11699. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11700. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11701. ktx.uploadLevels(_this._gl, !noMipmap);
  11702. return false;
  11703. }, samplingMode);
  11704. };
  11705. }
  11706. else if (isTGA) {
  11707. callback = function (arrayBuffer) {
  11708. var data = new Uint8Array(arrayBuffer);
  11709. var header = BABYLON.TGATools.GetTGAHeader(data);
  11710. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11711. BABYLON.TGATools.UploadContent(_this._gl, data);
  11712. return false;
  11713. }, samplingMode);
  11714. };
  11715. }
  11716. else if (isDDS) {
  11717. callback = function (data) {
  11718. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11719. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11720. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11721. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11722. return false;
  11723. }, samplingMode);
  11724. };
  11725. }
  11726. if (!buffer) {
  11727. this._loadFile(url, function (data) {
  11728. if (callback) {
  11729. callback(data);
  11730. }
  11731. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11732. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11733. });
  11734. }
  11735. else {
  11736. if (callback) {
  11737. callback(buffer);
  11738. }
  11739. }
  11740. // image format processing
  11741. }
  11742. else {
  11743. var onload = function (img) {
  11744. if (fromBlob && !_this._doNotHandleContextLost) {
  11745. // We need to store the image if we need to rebuild the texture
  11746. // in case of a webgl context lost
  11747. texture._buffer = img;
  11748. }
  11749. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11750. var gl = _this._gl;
  11751. var isPot = (img.width === potWidth && img.height === potHeight);
  11752. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11753. if (isPot) {
  11754. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11755. return false;
  11756. }
  11757. // Using shaders to rescale because canvas.drawImage is lossy
  11758. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11759. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11760. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11765. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11766. _this._releaseTexture(source);
  11767. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11768. continuationCallback();
  11769. });
  11770. return true;
  11771. }, samplingMode);
  11772. };
  11773. if (!fromData || isBase64)
  11774. if (buffer instanceof HTMLImageElement) {
  11775. onload(buffer);
  11776. }
  11777. else {
  11778. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11779. }
  11780. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11781. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11782. else
  11783. onload(buffer);
  11784. }
  11785. return texture;
  11786. };
  11787. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11788. var _this = this;
  11789. var rtt = this.createRenderTargetTexture({
  11790. width: destination.width,
  11791. height: destination.height,
  11792. }, {
  11793. generateMipMaps: false,
  11794. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11795. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11796. generateDepthBuffer: false,
  11797. generateStencilBuffer: false
  11798. });
  11799. if (!this._rescalePostProcess) {
  11800. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11801. }
  11802. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11803. _this._rescalePostProcess.onApply = function (effect) {
  11804. effect._bindTexture("textureSampler", source);
  11805. };
  11806. var hostingScene = scene;
  11807. if (!hostingScene) {
  11808. hostingScene = _this.scenes[_this.scenes.length - 1];
  11809. }
  11810. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11811. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11812. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11813. _this.unBindFramebuffer(rtt);
  11814. _this._releaseTexture(rtt);
  11815. if (onComplete) {
  11816. onComplete();
  11817. }
  11818. });
  11819. };
  11820. Engine.prototype._getInternalFormat = function (format) {
  11821. var internalFormat = this._gl.RGBA;
  11822. switch (format) {
  11823. case Engine.TEXTUREFORMAT_ALPHA:
  11824. internalFormat = this._gl.ALPHA;
  11825. break;
  11826. case Engine.TEXTUREFORMAT_LUMINANCE:
  11827. internalFormat = this._gl.LUMINANCE;
  11828. break;
  11829. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11830. internalFormat = this._gl.LUMINANCE_ALPHA;
  11831. break;
  11832. case Engine.TEXTUREFORMAT_RGB:
  11833. internalFormat = this._gl.RGB;
  11834. break;
  11835. case Engine.TEXTUREFORMAT_RGBA:
  11836. internalFormat = this._gl.RGBA;
  11837. break;
  11838. }
  11839. return internalFormat;
  11840. };
  11841. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11842. if (compression === void 0) { compression = null; }
  11843. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11844. if (!texture) {
  11845. return;
  11846. }
  11847. var internalFormat = this._getInternalFormat(format);
  11848. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11849. var textureType = this._getWebGLTextureType(type);
  11850. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11851. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11852. if (!this._doNotHandleContextLost) {
  11853. texture._bufferView = data;
  11854. texture.format = format;
  11855. texture.type = type;
  11856. texture.invertY = invertY;
  11857. texture._compression = compression;
  11858. }
  11859. if (texture.width % 4 !== 0) {
  11860. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11861. }
  11862. if (compression && data) {
  11863. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11864. }
  11865. else {
  11866. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11867. }
  11868. if (texture.generateMipMaps) {
  11869. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11870. }
  11871. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11872. // this.resetTextureCache();
  11873. texture.isReady = true;
  11874. };
  11875. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11876. if (compression === void 0) { compression = null; }
  11877. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11878. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11879. texture.baseWidth = width;
  11880. texture.baseHeight = height;
  11881. texture.width = width;
  11882. texture.height = height;
  11883. texture.format = format;
  11884. texture.generateMipMaps = generateMipMaps;
  11885. texture.samplingMode = samplingMode;
  11886. texture.invertY = invertY;
  11887. texture._compression = compression;
  11888. texture.type = type;
  11889. if (!this._doNotHandleContextLost) {
  11890. texture._bufferView = data;
  11891. }
  11892. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11893. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11894. // Filters
  11895. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11897. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11898. if (generateMipMaps) {
  11899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11900. }
  11901. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11902. this._internalTexturesCache.push(texture);
  11903. return texture;
  11904. };
  11905. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11906. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11907. texture.baseWidth = width;
  11908. texture.baseHeight = height;
  11909. if (generateMipMaps) {
  11910. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11911. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11912. }
  11913. // this.resetTextureCache();
  11914. texture.width = width;
  11915. texture.height = height;
  11916. texture.isReady = false;
  11917. texture.generateMipMaps = generateMipMaps;
  11918. texture.samplingMode = samplingMode;
  11919. this.updateTextureSamplingMode(samplingMode, texture);
  11920. this._internalTexturesCache.push(texture);
  11921. return texture;
  11922. };
  11923. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11924. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11925. if (texture.isCube) {
  11926. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11927. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11928. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11929. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11930. }
  11931. else if (texture.is3D) {
  11932. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11933. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11934. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11935. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11936. }
  11937. else {
  11938. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11939. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11940. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11941. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11942. }
  11943. texture.samplingMode = samplingMode;
  11944. };
  11945. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11946. if (premulAlpha === void 0) { premulAlpha = false; }
  11947. if (!texture) {
  11948. return;
  11949. }
  11950. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11951. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11952. if (premulAlpha) {
  11953. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11954. }
  11955. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11956. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11957. if (texture.generateMipMaps) {
  11958. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11959. }
  11960. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11961. if (premulAlpha) {
  11962. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11963. }
  11964. texture.isReady = true;
  11965. };
  11966. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11967. if (!texture || texture._isDisabled) {
  11968. return;
  11969. }
  11970. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11971. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11972. try {
  11973. // Testing video texture support
  11974. if (this._videoTextureSupported === undefined) {
  11975. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11976. if (this._gl.getError() !== 0) {
  11977. this._videoTextureSupported = false;
  11978. }
  11979. else {
  11980. this._videoTextureSupported = true;
  11981. }
  11982. }
  11983. // Copy video through the current working canvas if video texture is not supported
  11984. if (!this._videoTextureSupported) {
  11985. if (!texture._workingCanvas) {
  11986. texture._workingCanvas = document.createElement("canvas");
  11987. var context = texture._workingCanvas.getContext("2d");
  11988. if (!context) {
  11989. throw new Error("Unable to get 2d context");
  11990. }
  11991. texture._workingContext = context;
  11992. texture._workingCanvas.width = texture.width;
  11993. texture._workingCanvas.height = texture.height;
  11994. }
  11995. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11996. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11997. }
  11998. else {
  11999. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12000. }
  12001. if (texture.generateMipMaps) {
  12002. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12003. }
  12004. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12005. // this.resetTextureCache();
  12006. texture.isReady = true;
  12007. }
  12008. catch (ex) {
  12009. // Something unexpected
  12010. // Let's disable the texture
  12011. texture._isDisabled = true;
  12012. }
  12013. };
  12014. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12015. var fullOptions = new RenderTargetCreationOptions();
  12016. if (options !== undefined && typeof options === "object") {
  12017. fullOptions.generateMipMaps = options.generateMipMaps;
  12018. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12019. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12020. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12021. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12022. }
  12023. else {
  12024. fullOptions.generateMipMaps = options;
  12025. fullOptions.generateDepthBuffer = true;
  12026. fullOptions.generateStencilBuffer = false;
  12027. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12028. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12029. }
  12030. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12031. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12032. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12033. }
  12034. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12035. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12036. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12037. }
  12038. var gl = this._gl;
  12039. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12040. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12041. var width = size.width || size;
  12042. var height = size.height || size;
  12043. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12044. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12045. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12046. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12047. }
  12048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12049. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12050. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12051. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12052. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12053. // Create the framebuffer
  12054. var framebuffer = gl.createFramebuffer();
  12055. this.bindUnboundFramebuffer(framebuffer);
  12056. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12057. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12058. if (fullOptions.generateMipMaps) {
  12059. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12060. }
  12061. // Unbind
  12062. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12063. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12064. this.bindUnboundFramebuffer(null);
  12065. texture._framebuffer = framebuffer;
  12066. texture.baseWidth = width;
  12067. texture.baseHeight = height;
  12068. texture.width = width;
  12069. texture.height = height;
  12070. texture.isReady = true;
  12071. texture.samples = 1;
  12072. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12073. texture.samplingMode = fullOptions.samplingMode;
  12074. texture.type = fullOptions.type;
  12075. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12076. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12077. // this.resetTextureCache();
  12078. this._internalTexturesCache.push(texture);
  12079. return texture;
  12080. };
  12081. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12082. var generateMipMaps = false;
  12083. var generateDepthBuffer = true;
  12084. var generateStencilBuffer = false;
  12085. var generateDepthTexture = false;
  12086. var textureCount = 1;
  12087. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12088. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12089. var types = [], samplingModes = [];
  12090. if (options !== undefined) {
  12091. generateMipMaps = options.generateMipMaps;
  12092. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12093. generateStencilBuffer = options.generateStencilBuffer;
  12094. generateDepthTexture = options.generateDepthTexture;
  12095. textureCount = options.textureCount || 1;
  12096. if (options.types) {
  12097. types = options.types;
  12098. }
  12099. if (options.samplingModes) {
  12100. samplingModes = options.samplingModes;
  12101. }
  12102. }
  12103. var gl = this._gl;
  12104. // Create the framebuffer
  12105. var framebuffer = gl.createFramebuffer();
  12106. this.bindUnboundFramebuffer(framebuffer);
  12107. var width = size.width || size;
  12108. var height = size.height || size;
  12109. var textures = [];
  12110. var attachments = [];
  12111. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12112. for (var i = 0; i < textureCount; i++) {
  12113. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12114. var type = types[i] || defaultType;
  12115. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12116. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12117. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12118. }
  12119. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12120. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12121. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12122. }
  12123. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12124. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12125. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12126. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12127. }
  12128. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12129. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12130. textures.push(texture);
  12131. attachments.push(attachment);
  12132. gl.activeTexture(gl["TEXTURE" + i]);
  12133. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12134. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12135. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12136. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12137. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12138. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12139. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12140. if (generateMipMaps) {
  12141. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12142. }
  12143. // Unbind
  12144. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12145. texture._framebuffer = framebuffer;
  12146. texture._depthStencilBuffer = depthStencilBuffer;
  12147. texture.baseWidth = width;
  12148. texture.baseHeight = height;
  12149. texture.width = width;
  12150. texture.height = height;
  12151. texture.isReady = true;
  12152. texture.samples = 1;
  12153. texture.generateMipMaps = generateMipMaps;
  12154. texture.samplingMode = samplingMode;
  12155. texture.type = type;
  12156. texture._generateDepthBuffer = generateDepthBuffer;
  12157. texture._generateStencilBuffer = generateStencilBuffer;
  12158. texture._attachments = attachments;
  12159. this._internalTexturesCache.push(texture);
  12160. }
  12161. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12162. // Depth texture
  12163. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12164. gl.activeTexture(gl.TEXTURE0);
  12165. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12170. 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);
  12171. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12172. depthTexture._framebuffer = framebuffer;
  12173. depthTexture.baseWidth = width;
  12174. depthTexture.baseHeight = height;
  12175. depthTexture.width = width;
  12176. depthTexture.height = height;
  12177. depthTexture.isReady = true;
  12178. depthTexture.samples = 1;
  12179. depthTexture.generateMipMaps = generateMipMaps;
  12180. depthTexture.samplingMode = gl.NEAREST;
  12181. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12182. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12183. textures.push(depthTexture);
  12184. this._internalTexturesCache.push(depthTexture);
  12185. }
  12186. gl.drawBuffers(attachments);
  12187. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12188. this.bindUnboundFramebuffer(null);
  12189. this.resetTextureCache();
  12190. return textures;
  12191. };
  12192. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12193. if (samples === void 0) { samples = 1; }
  12194. var depthStencilBuffer = null;
  12195. var gl = this._gl;
  12196. // Create the depth/stencil buffer
  12197. if (generateStencilBuffer) {
  12198. depthStencilBuffer = gl.createRenderbuffer();
  12199. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12200. if (samples > 1) {
  12201. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12202. }
  12203. else {
  12204. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12205. }
  12206. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12207. }
  12208. else if (generateDepthBuffer) {
  12209. depthStencilBuffer = gl.createRenderbuffer();
  12210. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12211. if (samples > 1) {
  12212. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12213. }
  12214. else {
  12215. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12216. }
  12217. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12218. }
  12219. return depthStencilBuffer;
  12220. };
  12221. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12222. if (this.webGLVersion < 2 || !texture) {
  12223. return 1;
  12224. }
  12225. if (texture.samples === samples) {
  12226. return samples;
  12227. }
  12228. var gl = this._gl;
  12229. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12230. // Dispose previous render buffers
  12231. if (texture._depthStencilBuffer) {
  12232. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12233. texture._depthStencilBuffer = null;
  12234. }
  12235. if (texture._MSAAFramebuffer) {
  12236. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12237. texture._MSAAFramebuffer = null;
  12238. }
  12239. if (texture._MSAARenderBuffer) {
  12240. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12241. texture._MSAARenderBuffer = null;
  12242. }
  12243. if (samples > 1) {
  12244. var framebuffer = gl.createFramebuffer();
  12245. if (!framebuffer) {
  12246. throw new Error("Unable to create multi sampled framebuffer");
  12247. }
  12248. texture._MSAAFramebuffer = framebuffer;
  12249. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12250. var colorRenderbuffer = gl.createRenderbuffer();
  12251. if (!colorRenderbuffer) {
  12252. throw new Error("Unable to create multi sampled framebuffer");
  12253. }
  12254. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12255. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12256. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12257. texture._MSAARenderBuffer = colorRenderbuffer;
  12258. }
  12259. else {
  12260. this.bindUnboundFramebuffer(texture._framebuffer);
  12261. }
  12262. texture.samples = samples;
  12263. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12264. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12265. this.bindUnboundFramebuffer(null);
  12266. return samples;
  12267. };
  12268. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12269. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12270. return 1;
  12271. }
  12272. if (textures[0].samples === samples) {
  12273. return samples;
  12274. }
  12275. var gl = this._gl;
  12276. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12277. // Dispose previous render buffers
  12278. if (textures[0]._depthStencilBuffer) {
  12279. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12280. textures[0]._depthStencilBuffer = null;
  12281. }
  12282. if (textures[0]._MSAAFramebuffer) {
  12283. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12284. textures[0]._MSAAFramebuffer = null;
  12285. }
  12286. for (var i = 0; i < textures.length; i++) {
  12287. if (textures[i]._MSAARenderBuffer) {
  12288. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12289. textures[i]._MSAARenderBuffer = null;
  12290. }
  12291. }
  12292. if (samples > 1) {
  12293. var framebuffer = gl.createFramebuffer();
  12294. if (!framebuffer) {
  12295. throw new Error("Unable to create multi sampled framebuffer");
  12296. }
  12297. this.bindUnboundFramebuffer(framebuffer);
  12298. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12299. var attachments = [];
  12300. for (var i = 0; i < textures.length; i++) {
  12301. var texture = textures[i];
  12302. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12303. var colorRenderbuffer = gl.createRenderbuffer();
  12304. if (!colorRenderbuffer) {
  12305. throw new Error("Unable to create multi sampled framebuffer");
  12306. }
  12307. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12308. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12309. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12310. texture._MSAAFramebuffer = framebuffer;
  12311. texture._MSAARenderBuffer = colorRenderbuffer;
  12312. texture.samples = samples;
  12313. texture._depthStencilBuffer = depthStencilBuffer;
  12314. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12315. attachments.push(attachment);
  12316. }
  12317. gl.drawBuffers(attachments);
  12318. }
  12319. else {
  12320. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12321. }
  12322. this.bindUnboundFramebuffer(null);
  12323. return samples;
  12324. };
  12325. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12326. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12327. };
  12328. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12329. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12330. };
  12331. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12332. var gl = this._gl;
  12333. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12334. var generateMipMaps = true;
  12335. var generateDepthBuffer = true;
  12336. var generateStencilBuffer = false;
  12337. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12338. if (options !== undefined) {
  12339. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12340. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12341. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12342. if (options.samplingMode !== undefined) {
  12343. samplingMode = options.samplingMode;
  12344. }
  12345. }
  12346. texture.isCube = true;
  12347. texture.generateMipMaps = generateMipMaps;
  12348. texture.samples = 1;
  12349. texture.samplingMode = samplingMode;
  12350. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12351. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12352. for (var face = 0; face < 6; face++) {
  12353. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12354. }
  12355. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12356. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12357. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12358. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12359. // Create the framebuffer
  12360. var framebuffer = gl.createFramebuffer();
  12361. this.bindUnboundFramebuffer(framebuffer);
  12362. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12363. // Mipmaps
  12364. if (texture.generateMipMaps) {
  12365. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12366. }
  12367. // Unbind
  12368. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12369. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12370. this.bindUnboundFramebuffer(null);
  12371. texture._framebuffer = framebuffer;
  12372. texture.width = size;
  12373. texture.height = size;
  12374. texture.isReady = true;
  12375. //this.resetTextureCache();
  12376. this._internalTexturesCache.push(texture);
  12377. return texture;
  12378. };
  12379. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12380. var _this = this;
  12381. if (onLoad === void 0) { onLoad = null; }
  12382. if (onError === void 0) { onError = null; }
  12383. if (forcedExtension === void 0) { forcedExtension = null; }
  12384. var callback = function (loadData) {
  12385. if (!loadData) {
  12386. if (onLoad) {
  12387. onLoad(null);
  12388. }
  12389. return;
  12390. }
  12391. var texture = loadData.texture;
  12392. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12393. texture._lodGenerationScale = scale;
  12394. texture._lodGenerationOffset = offset;
  12395. if (_this._caps.textureLOD) {
  12396. // Do not add extra process if texture lod is supported.
  12397. if (onLoad) {
  12398. onLoad(texture);
  12399. }
  12400. return;
  12401. }
  12402. var mipSlices = 3;
  12403. var gl = _this._gl;
  12404. var width = loadData.width;
  12405. if (!width) {
  12406. return;
  12407. }
  12408. var textures = [];
  12409. for (var i = 0; i < mipSlices; i++) {
  12410. //compute LOD from even spacing in smoothness (matching shader calculation)
  12411. var smoothness = i / (mipSlices - 1);
  12412. var roughness = 1 - smoothness;
  12413. var minLODIndex = offset; // roughness = 0
  12414. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12415. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12416. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12417. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12418. glTextureFromLod.isCube = true;
  12419. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12424. if (loadData.isDDS) {
  12425. var info = loadData.info;
  12426. var data = loadData.data;
  12427. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12428. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12429. }
  12430. else {
  12431. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12432. }
  12433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12434. // Wrap in a base texture for easy binding.
  12435. var lodTexture = new BABYLON.BaseTexture(scene);
  12436. lodTexture.isCube = true;
  12437. lodTexture._texture = glTextureFromLod;
  12438. glTextureFromLod.isReady = true;
  12439. textures.push(lodTexture);
  12440. }
  12441. texture._lodTextureHigh = textures[2];
  12442. texture._lodTextureMid = textures[1];
  12443. texture._lodTextureLow = textures[0];
  12444. if (onLoad) {
  12445. onLoad(texture);
  12446. }
  12447. };
  12448. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12449. };
  12450. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12451. var _this = this;
  12452. if (onLoad === void 0) { onLoad = null; }
  12453. if (onError === void 0) { onError = null; }
  12454. if (forcedExtension === void 0) { forcedExtension = null; }
  12455. var gl = this._gl;
  12456. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12457. texture.isCube = true;
  12458. texture.url = rootUrl;
  12459. texture.generateMipMaps = !noMipmap;
  12460. if (!this._doNotHandleContextLost) {
  12461. texture._extension = forcedExtension;
  12462. texture._files = files;
  12463. }
  12464. var isKTX = false;
  12465. var isDDS = false;
  12466. var lastDot = rootUrl.lastIndexOf('.');
  12467. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12468. if (this._textureFormatInUse) {
  12469. extension = this._textureFormatInUse;
  12470. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12471. isKTX = true;
  12472. }
  12473. else {
  12474. isDDS = (extension === ".dds");
  12475. }
  12476. var onerror = function (request, exception) {
  12477. if (onError && request) {
  12478. onError(request.status + " " + request.statusText, exception);
  12479. }
  12480. };
  12481. if (isKTX) {
  12482. this._loadFile(rootUrl, function (data) {
  12483. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12484. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12485. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12486. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12487. ktx.uploadLevels(_this._gl, !noMipmap);
  12488. _this.setCubeMapTextureParams(gl, loadMipmap);
  12489. texture.width = ktx.pixelWidth;
  12490. texture.height = ktx.pixelHeight;
  12491. texture.isReady = true;
  12492. }, undefined, undefined, true, onerror);
  12493. }
  12494. else if (isDDS) {
  12495. if (files && files.length === 6) {
  12496. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12497. var info;
  12498. var loadMipmap = false;
  12499. var width = 0;
  12500. for (var index = 0; index < imgs.length; index++) {
  12501. var data = imgs[index];
  12502. info = BABYLON.DDSTools.GetDDSInfo(data);
  12503. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12504. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12505. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12506. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12507. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12508. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12509. }
  12510. texture.width = info.width;
  12511. texture.height = info.height;
  12512. texture.type = info.textureType;
  12513. width = info.width;
  12514. }
  12515. _this.setCubeMapTextureParams(gl, loadMipmap);
  12516. texture.isReady = true;
  12517. if (onLoad) {
  12518. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12519. }
  12520. }, files, onError);
  12521. }
  12522. else {
  12523. this._loadFile(rootUrl, function (data) {
  12524. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12525. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12526. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12527. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12528. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12529. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12530. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12531. }
  12532. _this.setCubeMapTextureParams(gl, loadMipmap);
  12533. texture.width = info.width;
  12534. texture.height = info.height;
  12535. texture.isReady = true;
  12536. texture.type = info.textureType;
  12537. if (onLoad) {
  12538. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12539. }
  12540. }, undefined, undefined, true, onerror);
  12541. }
  12542. }
  12543. else {
  12544. if (!files) {
  12545. throw new Error("Cannot load cubemap because files were not defined");
  12546. }
  12547. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12548. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12549. var height = width;
  12550. _this._prepareWorkingCanvas();
  12551. if (!_this._workingCanvas || !_this._workingContext) {
  12552. return;
  12553. }
  12554. _this._workingCanvas.width = width;
  12555. _this._workingCanvas.height = height;
  12556. var faces = [
  12557. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12558. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12559. ];
  12560. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12561. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12562. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12563. for (var index = 0; index < faces.length; index++) {
  12564. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12565. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12566. }
  12567. if (!noMipmap) {
  12568. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12569. }
  12570. _this.setCubeMapTextureParams(gl, !noMipmap);
  12571. texture.width = width;
  12572. texture.height = height;
  12573. texture.isReady = true;
  12574. if (format) {
  12575. texture.format = format;
  12576. }
  12577. texture.onLoadedObservable.notifyObservers(texture);
  12578. texture.onLoadedObservable.clear();
  12579. if (onLoad) {
  12580. onLoad();
  12581. }
  12582. }, files, onError);
  12583. }
  12584. this._internalTexturesCache.push(texture);
  12585. return texture;
  12586. };
  12587. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12592. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12593. // this.resetTextureCache();
  12594. };
  12595. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12596. if (compression === void 0) { compression = null; }
  12597. if (level === void 0) { level = 0; }
  12598. texture._bufferViewArray = data;
  12599. texture.format = format;
  12600. texture.type = type;
  12601. texture.invertY = invertY;
  12602. texture._compression = compression;
  12603. var gl = this._gl;
  12604. var textureType = this._getWebGLTextureType(type);
  12605. var internalFormat = this._getInternalFormat(format);
  12606. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12607. var needConversion = false;
  12608. if (internalFormat === gl.RGB) {
  12609. internalFormat = gl.RGBA;
  12610. needConversion = true;
  12611. }
  12612. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12613. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12614. if (texture.width % 4 !== 0) {
  12615. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12616. }
  12617. // Data are known to be in +X +Y +Z -X -Y -Z
  12618. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12619. var faceData = data[faceIndex];
  12620. if (compression) {
  12621. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12622. }
  12623. else {
  12624. if (needConversion) {
  12625. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12626. }
  12627. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12628. }
  12629. }
  12630. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12631. if (isPot && texture.generateMipMaps && level === 0) {
  12632. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12633. }
  12634. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12635. // this.resetTextureCache();
  12636. texture.isReady = true;
  12637. };
  12638. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12639. if (compression === void 0) { compression = null; }
  12640. var gl = this._gl;
  12641. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12642. texture.isCube = true;
  12643. texture.generateMipMaps = generateMipMaps;
  12644. texture.format = format;
  12645. texture.type = type;
  12646. if (!this._doNotHandleContextLost) {
  12647. texture._bufferViewArray = data;
  12648. }
  12649. var textureType = this._getWebGLTextureType(type);
  12650. var internalFormat = this._getInternalFormat(format);
  12651. if (internalFormat === gl.RGB) {
  12652. internalFormat = gl.RGBA;
  12653. }
  12654. var width = size;
  12655. var height = width;
  12656. texture.width = width;
  12657. texture.height = height;
  12658. // Double check on POT to generate Mips.
  12659. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12660. if (!isPot) {
  12661. generateMipMaps = false;
  12662. }
  12663. // Upload data if needed. The texture won't be ready until then.
  12664. if (data) {
  12665. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12666. }
  12667. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12668. // Filters
  12669. if (data && generateMipMaps) {
  12670. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12671. }
  12672. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12675. }
  12676. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12677. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12678. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12679. }
  12680. else {
  12681. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12684. }
  12685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12686. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12687. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12688. return texture;
  12689. };
  12690. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12691. var _this = this;
  12692. if (onLoad === void 0) { onLoad = null; }
  12693. if (onError === void 0) { onError = null; }
  12694. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12695. if (invertY === void 0) { invertY = false; }
  12696. var gl = this._gl;
  12697. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12698. scene._addPendingData(texture);
  12699. texture.url = url;
  12700. this._internalTexturesCache.push(texture);
  12701. var onerror = function (request, exception) {
  12702. scene._removePendingData(texture);
  12703. if (onError && request) {
  12704. onError(request.status + " " + request.statusText, exception);
  12705. }
  12706. };
  12707. var internalCallback = function (data) {
  12708. var width = texture.width;
  12709. var faceDataArrays = callback(data);
  12710. if (!faceDataArrays) {
  12711. return;
  12712. }
  12713. if (mipmmapGenerator) {
  12714. var textureType = _this._getWebGLTextureType(type);
  12715. var internalFormat = _this._getInternalFormat(format);
  12716. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12717. var needConversion = false;
  12718. if (internalFormat === gl.RGB) {
  12719. internalFormat = gl.RGBA;
  12720. needConversion = true;
  12721. }
  12722. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12723. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12724. var mipData = mipmmapGenerator(faceDataArrays);
  12725. for (var level = 0; level < mipData.length; level++) {
  12726. var mipSize = width >> level;
  12727. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12728. var mipFaceData = mipData[level][faceIndex];
  12729. if (needConversion) {
  12730. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12731. }
  12732. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12733. }
  12734. }
  12735. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12736. }
  12737. else {
  12738. texture.generateMipMaps = !noMipmap;
  12739. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12740. }
  12741. texture.isReady = true;
  12742. // this.resetTextureCache();
  12743. scene._removePendingData(texture);
  12744. if (onLoad) {
  12745. onLoad();
  12746. }
  12747. };
  12748. this._loadFile(url, function (data) {
  12749. internalCallback(data);
  12750. }, undefined, scene.database, true, onerror);
  12751. return texture;
  12752. };
  12753. ;
  12754. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12755. if (compression === void 0) { compression = null; }
  12756. var internalFormat = this._getInternalFormat(format);
  12757. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12758. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12759. if (!this._doNotHandleContextLost) {
  12760. texture._bufferView = data;
  12761. texture.format = format;
  12762. texture.invertY = invertY;
  12763. texture._compression = compression;
  12764. }
  12765. if (texture.width % 4 !== 0) {
  12766. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12767. }
  12768. if (compression && data) {
  12769. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12770. }
  12771. else {
  12772. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12773. }
  12774. if (texture.generateMipMaps) {
  12775. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12776. }
  12777. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12778. // this.resetTextureCache();
  12779. texture.isReady = true;
  12780. };
  12781. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12782. if (compression === void 0) { compression = null; }
  12783. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12784. texture.baseWidth = width;
  12785. texture.baseHeight = height;
  12786. texture.baseDepth = depth;
  12787. texture.width = width;
  12788. texture.height = height;
  12789. texture.depth = depth;
  12790. texture.format = format;
  12791. texture.generateMipMaps = generateMipMaps;
  12792. texture.samplingMode = samplingMode;
  12793. texture.is3D = true;
  12794. if (!this._doNotHandleContextLost) {
  12795. texture._bufferView = data;
  12796. }
  12797. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12798. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12799. // Filters
  12800. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12801. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12802. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12803. if (generateMipMaps) {
  12804. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12805. }
  12806. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12807. this._internalTexturesCache.push(texture);
  12808. return texture;
  12809. };
  12810. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12811. var gl = this._gl;
  12812. if (!gl) {
  12813. return;
  12814. }
  12815. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12816. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12817. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12818. if (!noMipmap && !isCompressed) {
  12819. gl.generateMipmap(gl.TEXTURE_2D);
  12820. }
  12821. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12822. // this.resetTextureCache();
  12823. if (scene) {
  12824. scene._removePendingData(texture);
  12825. }
  12826. texture.onLoadedObservable.notifyObservers(texture);
  12827. texture.onLoadedObservable.clear();
  12828. };
  12829. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12830. var _this = this;
  12831. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12832. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12833. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12834. var gl = this._gl;
  12835. if (!gl) {
  12836. return;
  12837. }
  12838. if (!texture._webGLTexture) {
  12839. // this.resetTextureCache();
  12840. if (scene) {
  12841. scene._removePendingData(texture);
  12842. }
  12843. return;
  12844. }
  12845. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12846. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12847. texture.baseWidth = width;
  12848. texture.baseHeight = height;
  12849. texture.width = potWidth;
  12850. texture.height = potHeight;
  12851. texture.isReady = true;
  12852. if (processFunction(potWidth, potHeight, function () {
  12853. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12854. })) {
  12855. // Returning as texture needs extra async steps
  12856. return;
  12857. }
  12858. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12859. };
  12860. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12861. // Create new RGBA data container.
  12862. var rgbaData;
  12863. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12864. rgbaData = new Float32Array(width * height * 4);
  12865. }
  12866. else {
  12867. rgbaData = new Uint32Array(width * height * 4);
  12868. }
  12869. // Convert each pixel.
  12870. for (var x = 0; x < width; x++) {
  12871. for (var y = 0; y < height; y++) {
  12872. var index = (y * width + x) * 3;
  12873. var newIndex = (y * width + x) * 4;
  12874. // Map Old Value to new value.
  12875. rgbaData[newIndex + 0] = rgbData[index + 0];
  12876. rgbaData[newIndex + 1] = rgbData[index + 1];
  12877. rgbaData[newIndex + 2] = rgbData[index + 2];
  12878. // Add fully opaque alpha channel.
  12879. rgbaData[newIndex + 3] = 1;
  12880. }
  12881. }
  12882. return rgbaData;
  12883. };
  12884. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12885. var gl = this._gl;
  12886. if (texture._framebuffer) {
  12887. gl.deleteFramebuffer(texture._framebuffer);
  12888. texture._framebuffer = null;
  12889. }
  12890. if (texture._depthStencilBuffer) {
  12891. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12892. texture._depthStencilBuffer = null;
  12893. }
  12894. if (texture._MSAAFramebuffer) {
  12895. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12896. texture._MSAAFramebuffer = null;
  12897. }
  12898. if (texture._MSAARenderBuffer) {
  12899. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12900. texture._MSAARenderBuffer = null;
  12901. }
  12902. };
  12903. Engine.prototype._releaseTexture = function (texture) {
  12904. var gl = this._gl;
  12905. this._releaseFramebufferObjects(texture);
  12906. gl.deleteTexture(texture._webGLTexture);
  12907. // Unbind channels
  12908. this.unbindAllTextures();
  12909. var index = this._internalTexturesCache.indexOf(texture);
  12910. if (index !== -1) {
  12911. this._internalTexturesCache.splice(index, 1);
  12912. }
  12913. // Integrated fixed lod samplers.
  12914. if (texture._lodTextureHigh) {
  12915. texture._lodTextureHigh.dispose();
  12916. }
  12917. if (texture._lodTextureMid) {
  12918. texture._lodTextureMid.dispose();
  12919. }
  12920. if (texture._lodTextureLow) {
  12921. texture._lodTextureLow.dispose();
  12922. }
  12923. };
  12924. Engine.prototype.setProgram = function (program) {
  12925. if (this._currentProgram !== program) {
  12926. this._gl.useProgram(program);
  12927. this._currentProgram = program;
  12928. }
  12929. };
  12930. Engine.prototype.bindSamplers = function (effect) {
  12931. this.setProgram(effect.getProgram());
  12932. var samplers = effect.getSamplers();
  12933. for (var index = 0; index < samplers.length; index++) {
  12934. var uniform = effect.getUniform(samplers[index]);
  12935. if (uniform) {
  12936. this._boundUniforms[index] = uniform;
  12937. }
  12938. }
  12939. this._currentEffect = null;
  12940. };
  12941. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12942. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  12943. return;
  12944. }
  12945. // Remove
  12946. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12947. // Bind last to it
  12948. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  12949. // Bind to dummy
  12950. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  12951. };
  12952. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12953. if (!internalTexture) {
  12954. return -1;
  12955. }
  12956. internalTexture._initialSlot = channel;
  12957. if (this.disableTextureBindingOptimization) {
  12958. if (channel !== internalTexture._designatedSlot) {
  12959. this._textureCollisions.addCount(1, false);
  12960. }
  12961. }
  12962. else {
  12963. if (channel !== internalTexture._designatedSlot) {
  12964. if (internalTexture._designatedSlot > -1) {
  12965. return internalTexture._designatedSlot;
  12966. }
  12967. else {
  12968. // No slot for this texture, let's pick a new one (if we find a free slot)
  12969. if (this._nextFreeTextureSlots.length) {
  12970. return this._nextFreeTextureSlots[0];
  12971. }
  12972. // We need to recycle the oldest bound texture, sorry.
  12973. this._textureCollisions.addCount(1, false);
  12974. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  12975. }
  12976. }
  12977. }
  12978. return channel;
  12979. };
  12980. Engine.prototype._linkTrackers = function (previous, next) {
  12981. previous.next = next;
  12982. next.previous = previous;
  12983. };
  12984. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12985. var currentSlot = internalTexture._designatedSlot;
  12986. if (currentSlot === -1) {
  12987. return -1;
  12988. }
  12989. internalTexture._designatedSlot = -1;
  12990. // Remove from bound list
  12991. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12992. // Free the slot
  12993. this._boundTexturesCache[currentSlot] = null;
  12994. this._nextFreeTextureSlots.push(currentSlot);
  12995. return currentSlot;
  12996. };
  12997. Engine.prototype._activateCurrentTexture = function () {
  12998. if (this._currentTextureChannel !== this._activeChannel) {
  12999. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13000. this._currentTextureChannel = this._activeChannel;
  13001. }
  13002. };
  13003. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13004. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13005. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13006. this._activeChannel = texture._designatedSlot;
  13007. }
  13008. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13009. var isTextureForRendering = texture && texture._initialSlot > -1;
  13010. if (currentTextureBound !== texture) {
  13011. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  13012. this._removeDesignatedSlot(currentTextureBound);
  13013. }
  13014. this._activateCurrentTexture();
  13015. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13016. this._boundTexturesCache[this._activeChannel] = texture;
  13017. if (texture) {
  13018. if (!this.disableTextureBindingOptimization) {
  13019. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13020. if (slotIndex > -1) {
  13021. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13022. }
  13023. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13024. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13025. }
  13026. texture._designatedSlot = this._activeChannel;
  13027. }
  13028. }
  13029. else if (forTextureDataUpdate) {
  13030. this._activateCurrentTexture();
  13031. }
  13032. if (isTextureForRendering && !forTextureDataUpdate) {
  13033. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13034. }
  13035. };
  13036. Engine.prototype._bindTexture = function (channel, texture) {
  13037. if (channel < 0) {
  13038. return;
  13039. }
  13040. if (texture) {
  13041. channel = this._getCorrectTextureChannel(channel, texture);
  13042. }
  13043. this._activeChannel = channel;
  13044. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13045. };
  13046. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13047. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13048. };
  13049. Engine.prototype.unbindAllTextures = function () {
  13050. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13051. this._activeChannel = channel;
  13052. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13053. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13054. if (this.webGLVersion > 1) {
  13055. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13056. }
  13057. }
  13058. };
  13059. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13060. if (channel < 0) {
  13061. return;
  13062. }
  13063. if (uniform) {
  13064. this._boundUniforms[channel] = uniform;
  13065. }
  13066. this._setTexture(channel, texture);
  13067. };
  13068. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13069. var uniform = this._boundUniforms[sourceSlot];
  13070. if (uniform._currentState === destination) {
  13071. return;
  13072. }
  13073. this._gl.uniform1i(uniform, destination);
  13074. uniform._currentState = destination;
  13075. };
  13076. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13077. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13078. // Not ready?
  13079. if (!texture) {
  13080. if (this._boundTexturesCache[channel] != null) {
  13081. this._activeChannel = channel;
  13082. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13083. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13084. if (this.webGLVersion > 1) {
  13085. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13086. }
  13087. }
  13088. return false;
  13089. }
  13090. // Video
  13091. if (texture.video) {
  13092. this._activeChannel = channel;
  13093. texture.update();
  13094. }
  13095. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13096. texture.delayLoad();
  13097. return false;
  13098. }
  13099. var internalTexture;
  13100. if (texture.isReady()) {
  13101. internalTexture = texture.getInternalTexture();
  13102. }
  13103. else if (texture.isCube) {
  13104. internalTexture = this.emptyCubeTexture;
  13105. }
  13106. else if (texture.is3D) {
  13107. internalTexture = this.emptyTexture3D;
  13108. }
  13109. else {
  13110. internalTexture = this.emptyTexture;
  13111. }
  13112. if (!isPartOfTextureArray) {
  13113. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13114. }
  13115. if (this._boundTexturesCache[channel] === internalTexture) {
  13116. this._moveBoundTextureOnTop(internalTexture);
  13117. if (!isPartOfTextureArray) {
  13118. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13119. }
  13120. return false;
  13121. }
  13122. this._activeChannel = channel;
  13123. if (internalTexture && internalTexture.is3D) {
  13124. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13125. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13126. internalTexture._cachedWrapU = texture.wrapU;
  13127. switch (texture.wrapU) {
  13128. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13129. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13130. break;
  13131. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13132. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13133. break;
  13134. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13135. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13136. break;
  13137. }
  13138. }
  13139. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13140. internalTexture._cachedWrapV = texture.wrapV;
  13141. switch (texture.wrapV) {
  13142. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13143. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13144. break;
  13145. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13146. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13147. break;
  13148. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13149. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13150. break;
  13151. }
  13152. }
  13153. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13154. internalTexture._cachedWrapR = texture.wrapR;
  13155. switch (texture.wrapV) {
  13156. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13157. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13158. break;
  13159. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13160. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13161. break;
  13162. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13164. break;
  13165. }
  13166. }
  13167. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13168. }
  13169. else if (internalTexture && internalTexture.isCube) {
  13170. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13171. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13172. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13173. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13174. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13175. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13176. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13177. }
  13178. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13179. }
  13180. else {
  13181. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13182. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13183. internalTexture._cachedWrapU = texture.wrapU;
  13184. switch (texture.wrapU) {
  13185. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13186. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13187. break;
  13188. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13189. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13190. break;
  13191. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13192. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13193. break;
  13194. }
  13195. }
  13196. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13197. internalTexture._cachedWrapV = texture.wrapV;
  13198. switch (texture.wrapV) {
  13199. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13201. break;
  13202. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13204. break;
  13205. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13207. break;
  13208. }
  13209. }
  13210. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13211. }
  13212. return true;
  13213. };
  13214. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13215. if (channel < 0 || !uniform) {
  13216. return;
  13217. }
  13218. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13219. this._textureUnits = new Int32Array(textures.length);
  13220. }
  13221. for (var i = 0; i < textures.length; i++) {
  13222. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13223. }
  13224. this._gl.uniform1iv(uniform, this._textureUnits);
  13225. for (var index = 0; index < textures.length; index++) {
  13226. this._setTexture(this._textureUnits[index], textures[index], true);
  13227. }
  13228. };
  13229. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13230. var internalTexture = texture.getInternalTexture();
  13231. if (!internalTexture) {
  13232. return;
  13233. }
  13234. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13235. var value = texture.anisotropicFilteringLevel;
  13236. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13237. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13238. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13239. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13240. }
  13241. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13242. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13243. internalTexture._cachedAnisotropicFilteringLevel = value;
  13244. }
  13245. };
  13246. Engine.prototype.readPixels = function (x, y, width, height) {
  13247. var data = new Uint8Array(height * width * 4);
  13248. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13249. return data;
  13250. };
  13251. /**
  13252. * Add an externaly attached data from its key.
  13253. * This method call will fail and return false, if such key already exists.
  13254. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13255. * @param key the unique key that identifies the data
  13256. * @param data the data object to associate to the key for this Engine instance
  13257. * @return true if no such key were already present and the data was added successfully, false otherwise
  13258. */
  13259. Engine.prototype.addExternalData = function (key, data) {
  13260. if (!this._externalData) {
  13261. this._externalData = new BABYLON.StringDictionary();
  13262. }
  13263. return this._externalData.add(key, data);
  13264. };
  13265. /**
  13266. * Get an externaly attached data from its key
  13267. * @param key the unique key that identifies the data
  13268. * @return the associated data, if present (can be null), or undefined if not present
  13269. */
  13270. Engine.prototype.getExternalData = function (key) {
  13271. if (!this._externalData) {
  13272. this._externalData = new BABYLON.StringDictionary();
  13273. }
  13274. return this._externalData.get(key);
  13275. };
  13276. /**
  13277. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13278. * @param key the unique key that identifies the data
  13279. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13280. * @return the associated data, can be null if the factory returned null.
  13281. */
  13282. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13283. if (!this._externalData) {
  13284. this._externalData = new BABYLON.StringDictionary();
  13285. }
  13286. return this._externalData.getOrAddWithFactory(key, factory);
  13287. };
  13288. /**
  13289. * Remove an externaly attached data from the Engine instance
  13290. * @param key the unique key that identifies the data
  13291. * @return true if the data was successfully removed, false if it doesn't exist
  13292. */
  13293. Engine.prototype.removeExternalData = function (key) {
  13294. if (!this._externalData) {
  13295. this._externalData = new BABYLON.StringDictionary();
  13296. }
  13297. return this._externalData.remove(key);
  13298. };
  13299. Engine.prototype.unbindAllAttributes = function () {
  13300. if (this._mustWipeVertexAttributes) {
  13301. this._mustWipeVertexAttributes = false;
  13302. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13303. this._gl.disableVertexAttribArray(i);
  13304. this._vertexAttribArraysEnabled[i] = false;
  13305. this._currentBufferPointers[i].active = false;
  13306. }
  13307. return;
  13308. }
  13309. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13310. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13311. continue;
  13312. }
  13313. this._gl.disableVertexAttribArray(i);
  13314. this._vertexAttribArraysEnabled[i] = false;
  13315. this._currentBufferPointers[i].active = false;
  13316. }
  13317. };
  13318. Engine.prototype.releaseEffects = function () {
  13319. for (var name in this._compiledEffects) {
  13320. this._deleteProgram(this._compiledEffects[name]._program);
  13321. }
  13322. this._compiledEffects = {};
  13323. };
  13324. // Dispose
  13325. Engine.prototype.dispose = function () {
  13326. this.hideLoadingUI();
  13327. this.stopRenderLoop();
  13328. // Release postProcesses
  13329. while (this.postProcesses.length) {
  13330. this.postProcesses[0].dispose();
  13331. }
  13332. // Empty texture
  13333. if (this._emptyTexture) {
  13334. this._releaseTexture(this._emptyTexture);
  13335. this._emptyTexture = null;
  13336. }
  13337. if (this._emptyCubeTexture) {
  13338. this._releaseTexture(this._emptyCubeTexture);
  13339. this._emptyCubeTexture = null;
  13340. }
  13341. // Rescale PP
  13342. if (this._rescalePostProcess) {
  13343. this._rescalePostProcess.dispose();
  13344. }
  13345. // Release scenes
  13346. while (this.scenes.length) {
  13347. this.scenes[0].dispose();
  13348. }
  13349. // Release audio engine
  13350. if (Engine.audioEngine) {
  13351. Engine.audioEngine.dispose();
  13352. }
  13353. // Release effects
  13354. this.releaseEffects();
  13355. // Unbind
  13356. this.unbindAllAttributes();
  13357. if (this._dummyFramebuffer) {
  13358. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13359. }
  13360. //WebVR
  13361. this.disableVR();
  13362. // Events
  13363. if (BABYLON.Tools.IsWindowObjectExist()) {
  13364. window.removeEventListener("blur", this._onBlur);
  13365. window.removeEventListener("focus", this._onFocus);
  13366. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13367. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13368. if (this._renderingCanvas) {
  13369. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13370. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13371. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13372. if (!this._doNotHandleContextLost) {
  13373. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13374. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13375. }
  13376. }
  13377. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13378. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13379. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13380. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13381. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13382. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13383. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13384. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13385. if (this._onVrDisplayConnect) {
  13386. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13387. if (this._onVrDisplayDisconnect) {
  13388. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13389. }
  13390. if (this._onVrDisplayPresentChange) {
  13391. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13392. }
  13393. this._onVrDisplayConnect = null;
  13394. this._onVrDisplayDisconnect = null;
  13395. }
  13396. }
  13397. // Remove from Instances
  13398. var index = Engine.Instances.indexOf(this);
  13399. if (index >= 0) {
  13400. Engine.Instances.splice(index, 1);
  13401. }
  13402. this._workingCanvas = null;
  13403. this._workingContext = null;
  13404. this._currentBufferPointers = [];
  13405. this._renderingCanvas = null;
  13406. this._currentProgram = null;
  13407. this.onResizeObservable.clear();
  13408. this.onCanvasBlurObservable.clear();
  13409. this.onCanvasFocusObservable.clear();
  13410. this.onCanvasPointerOutObservable.clear();
  13411. this.onBeginFrameObservable.clear();
  13412. this.onEndFrameObservable.clear();
  13413. BABYLON.Effect.ResetCache();
  13414. // Abort active requests
  13415. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13416. var request = _a[_i];
  13417. request.abort();
  13418. }
  13419. };
  13420. // Loading screen
  13421. Engine.prototype.displayLoadingUI = function () {
  13422. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13423. return;
  13424. }
  13425. var loadingScreen = this.loadingScreen;
  13426. if (loadingScreen) {
  13427. loadingScreen.displayLoadingUI();
  13428. }
  13429. };
  13430. Engine.prototype.hideLoadingUI = function () {
  13431. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13432. return;
  13433. }
  13434. var loadingScreen = this.loadingScreen;
  13435. if (loadingScreen) {
  13436. loadingScreen.hideLoadingUI();
  13437. }
  13438. };
  13439. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13440. get: function () {
  13441. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13442. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13443. return this._loadingScreen;
  13444. },
  13445. set: function (loadingScreen) {
  13446. this._loadingScreen = loadingScreen;
  13447. },
  13448. enumerable: true,
  13449. configurable: true
  13450. });
  13451. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13452. set: function (text) {
  13453. this.loadingScreen.loadingUIText = text;
  13454. },
  13455. enumerable: true,
  13456. configurable: true
  13457. });
  13458. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13459. set: function (color) {
  13460. this.loadingScreen.loadingUIBackgroundColor = color;
  13461. },
  13462. enumerable: true,
  13463. configurable: true
  13464. });
  13465. Engine.prototype.attachContextLostEvent = function (callback) {
  13466. if (this._renderingCanvas) {
  13467. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13468. }
  13469. };
  13470. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13471. if (this._renderingCanvas) {
  13472. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13473. }
  13474. };
  13475. Engine.prototype.getVertexShaderSource = function (program) {
  13476. var shaders = this._gl.getAttachedShaders(program);
  13477. if (!shaders) {
  13478. return null;
  13479. }
  13480. return this._gl.getShaderSource(shaders[0]);
  13481. };
  13482. Engine.prototype.getFragmentShaderSource = function (program) {
  13483. var shaders = this._gl.getAttachedShaders(program);
  13484. if (!shaders) {
  13485. return null;
  13486. }
  13487. return this._gl.getShaderSource(shaders[1]);
  13488. };
  13489. Engine.prototype.getError = function () {
  13490. return this._gl.getError();
  13491. };
  13492. // FPS
  13493. Engine.prototype.getFps = function () {
  13494. return this._fps;
  13495. };
  13496. Engine.prototype.getDeltaTime = function () {
  13497. return this._deltaTime;
  13498. };
  13499. Engine.prototype._measureFps = function () {
  13500. this._performanceMonitor.sampleFrame();
  13501. this._fps = this._performanceMonitor.averageFPS;
  13502. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13503. };
  13504. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13505. if (faceIndex === void 0) { faceIndex = -1; }
  13506. var gl = this._gl;
  13507. if (!this._dummyFramebuffer) {
  13508. var dummy = gl.createFramebuffer();
  13509. if (!dummy) {
  13510. throw new Error("Unable to create dummy framebuffer");
  13511. }
  13512. this._dummyFramebuffer = dummy;
  13513. }
  13514. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13515. if (faceIndex > -1) {
  13516. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13517. }
  13518. else {
  13519. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13520. }
  13521. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13522. var buffer;
  13523. switch (readType) {
  13524. case gl.UNSIGNED_BYTE:
  13525. buffer = new Uint8Array(4 * width * height);
  13526. readType = gl.UNSIGNED_BYTE;
  13527. break;
  13528. default:
  13529. buffer = new Float32Array(4 * width * height);
  13530. readType = gl.FLOAT;
  13531. break;
  13532. }
  13533. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13534. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13535. return buffer;
  13536. };
  13537. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13538. if (this._webGLVersion > 1) {
  13539. return this._caps.colorBufferFloat;
  13540. }
  13541. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13542. };
  13543. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13544. if (this._webGLVersion > 1) {
  13545. return this._caps.colorBufferFloat;
  13546. }
  13547. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13548. };
  13549. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13550. Engine.prototype._canRenderToFramebuffer = function (type) {
  13551. var gl = this._gl;
  13552. //clear existing errors
  13553. while (gl.getError() !== gl.NO_ERROR) { }
  13554. var successful = true;
  13555. var texture = gl.createTexture();
  13556. gl.bindTexture(gl.TEXTURE_2D, texture);
  13557. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13558. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13559. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13560. var fb = gl.createFramebuffer();
  13561. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13562. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13563. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13564. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13565. successful = successful && (gl.getError() === gl.NO_ERROR);
  13566. //try render by clearing frame buffer's color buffer
  13567. if (successful) {
  13568. gl.clear(gl.COLOR_BUFFER_BIT);
  13569. successful = successful && (gl.getError() === gl.NO_ERROR);
  13570. }
  13571. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13572. if (successful) {
  13573. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13574. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13575. var readFormat = gl.RGBA;
  13576. var readType = gl.UNSIGNED_BYTE;
  13577. var buffer = new Uint8Array(4);
  13578. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13579. successful = successful && (gl.getError() === gl.NO_ERROR);
  13580. }
  13581. //clean up
  13582. gl.deleteTexture(texture);
  13583. gl.deleteFramebuffer(fb);
  13584. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13585. //clear accumulated errors
  13586. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13587. return successful;
  13588. };
  13589. Engine.prototype._getWebGLTextureType = function (type) {
  13590. if (type === Engine.TEXTURETYPE_FLOAT) {
  13591. return this._gl.FLOAT;
  13592. }
  13593. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13594. // Add Half Float Constant.
  13595. return this._gl.HALF_FLOAT_OES;
  13596. }
  13597. return this._gl.UNSIGNED_BYTE;
  13598. };
  13599. ;
  13600. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13601. if (this._webGLVersion === 1) {
  13602. return this._gl.RGBA;
  13603. }
  13604. if (type === Engine.TEXTURETYPE_FLOAT) {
  13605. return this._gl.RGBA32F;
  13606. }
  13607. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13608. return this._gl.RGBA16F;
  13609. }
  13610. return this._gl.RGBA;
  13611. };
  13612. ;
  13613. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13614. if (type === Engine.TEXTURETYPE_FLOAT) {
  13615. return this._gl.RGBA32F;
  13616. }
  13617. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13618. return this._gl.RGBA16F;
  13619. }
  13620. return this._gl.RGBA8;
  13621. };
  13622. ;
  13623. Engine.prototype.createQuery = function () {
  13624. return this._gl.createQuery();
  13625. };
  13626. Engine.prototype.deleteQuery = function (query) {
  13627. this._gl.deleteQuery(query);
  13628. return this;
  13629. };
  13630. Engine.prototype.isQueryResultAvailable = function (query) {
  13631. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13632. };
  13633. Engine.prototype.getQueryResult = function (query) {
  13634. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13635. };
  13636. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13637. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13638. this._gl.beginQuery(glAlgorithm, query);
  13639. return this;
  13640. };
  13641. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13642. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13643. this._gl.endQuery(glAlgorithm);
  13644. return this;
  13645. };
  13646. /* Time queries */
  13647. Engine.prototype._createTimeQuery = function () {
  13648. var timerQuery = this._caps.timerQuery;
  13649. if (timerQuery.createQueryEXT) {
  13650. return timerQuery.createQueryEXT();
  13651. }
  13652. return this.createQuery();
  13653. };
  13654. Engine.prototype._deleteTimeQuery = function (query) {
  13655. var timerQuery = this._caps.timerQuery;
  13656. if (timerQuery.deleteQueryEXT) {
  13657. timerQuery.deleteQueryEXT(query);
  13658. return;
  13659. }
  13660. this.deleteQuery(query);
  13661. };
  13662. Engine.prototype._getTimeQueryResult = function (query) {
  13663. var timerQuery = this._caps.timerQuery;
  13664. if (timerQuery.getQueryObjectEXT) {
  13665. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13666. }
  13667. return this.getQueryResult(query);
  13668. };
  13669. Engine.prototype._getTimeQueryAvailability = function (query) {
  13670. var timerQuery = this._caps.timerQuery;
  13671. if (timerQuery.getQueryObjectEXT) {
  13672. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13673. }
  13674. return this.isQueryResultAvailable(query);
  13675. };
  13676. Engine.prototype.startTimeQuery = function () {
  13677. var timerQuery = this._caps.timerQuery;
  13678. if (!timerQuery) {
  13679. return null;
  13680. }
  13681. var token = new BABYLON._TimeToken();
  13682. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13683. if (this._caps.canUseTimestampForTimerQuery) {
  13684. token._startTimeQuery = this._createTimeQuery();
  13685. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13686. }
  13687. else {
  13688. if (this._currentNonTimestampToken) {
  13689. return this._currentNonTimestampToken;
  13690. }
  13691. token._timeElapsedQuery = this._createTimeQuery();
  13692. if (timerQuery.beginQueryEXT) {
  13693. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13694. }
  13695. else {
  13696. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13697. }
  13698. this._currentNonTimestampToken = token;
  13699. }
  13700. return token;
  13701. };
  13702. Engine.prototype.endTimeQuery = function (token) {
  13703. var timerQuery = this._caps.timerQuery;
  13704. if (!timerQuery || !token) {
  13705. return -1;
  13706. }
  13707. if (this._caps.canUseTimestampForTimerQuery) {
  13708. if (!token._startTimeQuery) {
  13709. return -1;
  13710. }
  13711. if (!token._endTimeQuery) {
  13712. token._endTimeQuery = this._createTimeQuery();
  13713. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13714. }
  13715. }
  13716. else if (!token._timeElapsedQueryEnded) {
  13717. if (!token._timeElapsedQuery) {
  13718. return -1;
  13719. }
  13720. if (timerQuery.endQueryEXT) {
  13721. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13722. }
  13723. else {
  13724. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13725. }
  13726. token._timeElapsedQueryEnded = true;
  13727. }
  13728. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13729. var available = false;
  13730. if (token._endTimeQuery) {
  13731. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13732. }
  13733. else if (token._timeElapsedQuery) {
  13734. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13735. }
  13736. if (available && !disjoint) {
  13737. var result = 0;
  13738. if (this._caps.canUseTimestampForTimerQuery) {
  13739. if (!token._startTimeQuery || !token._endTimeQuery) {
  13740. return -1;
  13741. }
  13742. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13743. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13744. result = timeEnd - timeStart;
  13745. this._deleteTimeQuery(token._startTimeQuery);
  13746. this._deleteTimeQuery(token._endTimeQuery);
  13747. token._startTimeQuery = null;
  13748. token._endTimeQuery = null;
  13749. }
  13750. else {
  13751. if (!token._timeElapsedQuery) {
  13752. return -1;
  13753. }
  13754. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13755. this._deleteTimeQuery(token._timeElapsedQuery);
  13756. token._timeElapsedQuery = null;
  13757. token._timeElapsedQueryEnded = false;
  13758. this._currentNonTimestampToken = null;
  13759. }
  13760. return result;
  13761. }
  13762. return -1;
  13763. };
  13764. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13765. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13766. };
  13767. // Transform feedback
  13768. Engine.prototype.createTransformFeedback = function () {
  13769. return this._gl.createTransformFeedback();
  13770. };
  13771. Engine.prototype.deleteTransformFeedback = function (value) {
  13772. this._gl.deleteTransformFeedback(value);
  13773. };
  13774. Engine.prototype.bindTransformFeedback = function (value) {
  13775. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13776. };
  13777. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13778. if (usePoints === void 0) { usePoints = true; }
  13779. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13780. };
  13781. Engine.prototype.endTransformFeedback = function () {
  13782. this._gl.endTransformFeedback();
  13783. };
  13784. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13785. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13786. };
  13787. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13788. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13789. };
  13790. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13791. var _this = this;
  13792. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13793. this._activeRequests.push(request);
  13794. request.onCompleteObservable.add(function (request) {
  13795. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13796. });
  13797. return request;
  13798. };
  13799. /** @ignore */
  13800. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  13801. var _this = this;
  13802. return new Promise(function (resolve, reject) {
  13803. _this._loadFile(url, function (data) {
  13804. resolve(data);
  13805. }, undefined, database, useArrayBuffer, function (request, exception) {
  13806. reject(exception);
  13807. });
  13808. });
  13809. };
  13810. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13811. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13812. var onload = function (data) {
  13813. loadedFiles[index] = data;
  13814. loadedFiles._internalCount++;
  13815. if (loadedFiles._internalCount === 6) {
  13816. onfinish(loadedFiles);
  13817. }
  13818. };
  13819. var onerror = function (request, exception) {
  13820. if (onErrorCallBack && request) {
  13821. onErrorCallBack(request.status + " " + request.statusText, exception);
  13822. }
  13823. };
  13824. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13825. };
  13826. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13827. if (onError === void 0) { onError = null; }
  13828. var loadedFiles = [];
  13829. loadedFiles._internalCount = 0;
  13830. for (var index = 0; index < 6; index++) {
  13831. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13832. }
  13833. };
  13834. // Statics
  13835. Engine.isSupported = function () {
  13836. try {
  13837. var tempcanvas = document.createElement("canvas");
  13838. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13839. return gl != null && !!window.WebGLRenderingContext;
  13840. }
  13841. catch (e) {
  13842. return false;
  13843. }
  13844. };
  13845. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13846. Engine.ExceptionList = [
  13847. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13848. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13849. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13850. ];
  13851. Engine.Instances = new Array();
  13852. // Const statics
  13853. Engine._ALPHA_DISABLE = 0;
  13854. Engine._ALPHA_ADD = 1;
  13855. Engine._ALPHA_COMBINE = 2;
  13856. Engine._ALPHA_SUBTRACT = 3;
  13857. Engine._ALPHA_MULTIPLY = 4;
  13858. Engine._ALPHA_MAXIMIZED = 5;
  13859. Engine._ALPHA_ONEONE = 6;
  13860. Engine._ALPHA_PREMULTIPLIED = 7;
  13861. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13862. Engine._ALPHA_INTERPOLATE = 9;
  13863. Engine._ALPHA_SCREENMODE = 10;
  13864. Engine._DELAYLOADSTATE_NONE = 0;
  13865. Engine._DELAYLOADSTATE_LOADED = 1;
  13866. Engine._DELAYLOADSTATE_LOADING = 2;
  13867. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13868. Engine._TEXTUREFORMAT_ALPHA = 0;
  13869. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13870. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13871. Engine._TEXTUREFORMAT_RGB = 4;
  13872. Engine._TEXTUREFORMAT_RGBA = 5;
  13873. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13874. Engine._TEXTURETYPE_FLOAT = 1;
  13875. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13876. // Depht or Stencil test Constants.
  13877. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13878. Engine._ALWAYS = 0x0207; // 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.
  13879. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  13880. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  13881. Engine._LEQUAL = 0x0203; // 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.
  13882. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  13883. Engine._GEQUAL = 0x0206; // 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.
  13884. Engine._NOTEQUAL = 0x0205; // 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.
  13885. // Stencil Actions Constants.
  13886. Engine._KEEP = 0x1E00;
  13887. Engine._REPLACE = 0x1E01;
  13888. Engine._INCR = 0x1E02;
  13889. Engine._DECR = 0x1E03;
  13890. Engine._INVERT = 0x150A;
  13891. Engine._INCR_WRAP = 0x8507;
  13892. Engine._DECR_WRAP = 0x8508;
  13893. // Texture rescaling mode
  13894. Engine._SCALEMODE_FLOOR = 1;
  13895. Engine._SCALEMODE_NEAREST = 2;
  13896. Engine._SCALEMODE_CEILING = 3;
  13897. // Updatable statics so stick with vars here
  13898. Engine.CollisionsEpsilon = 0.001;
  13899. Engine.CodeRepository = "src/";
  13900. Engine.ShadersRepository = "src/Shaders/";
  13901. return Engine;
  13902. }());
  13903. BABYLON.Engine = Engine;
  13904. })(BABYLON || (BABYLON = {}));
  13905. //# sourceMappingURL=babylon.engine.js.map
  13906. var BABYLON;
  13907. (function (BABYLON) {
  13908. /**
  13909. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13910. */
  13911. var Node = /** @class */ (function () {
  13912. /**
  13913. * @constructor
  13914. * @param {string} name - the name and id to be given to this node
  13915. * @param {BABYLON.Scene} the scene this node will be added to
  13916. */
  13917. function Node(name, scene) {
  13918. if (scene === void 0) { scene = null; }
  13919. this.state = "";
  13920. this.metadata = null;
  13921. this.doNotSerialize = false;
  13922. this.animations = new Array();
  13923. this._ranges = {};
  13924. this._isEnabled = true;
  13925. this._isReady = true;
  13926. this._currentRenderId = -1;
  13927. this._parentRenderId = -1;
  13928. /**
  13929. * An event triggered when the mesh is disposed.
  13930. * @type {BABYLON.Observable}
  13931. */
  13932. this.onDisposeObservable = new BABYLON.Observable();
  13933. // Behaviors
  13934. this._behaviors = new Array();
  13935. this.name = name;
  13936. this.id = name;
  13937. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13938. this.uniqueId = this._scene.getUniqueId();
  13939. this._initCache();
  13940. }
  13941. Object.defineProperty(Node.prototype, "parent", {
  13942. get: function () {
  13943. return this._parentNode;
  13944. },
  13945. set: function (parent) {
  13946. if (this._parentNode === parent) {
  13947. return;
  13948. }
  13949. // Remove self from list of children of parent
  13950. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13951. var index = this._parentNode._children.indexOf(this);
  13952. if (index !== -1) {
  13953. this._parentNode._children.splice(index, 1);
  13954. }
  13955. }
  13956. // Store new parent
  13957. this._parentNode = parent;
  13958. // Add as child to new parent
  13959. if (this._parentNode) {
  13960. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13961. this._parentNode._children = new Array();
  13962. }
  13963. this._parentNode._children.push(this);
  13964. }
  13965. },
  13966. enumerable: true,
  13967. configurable: true
  13968. });
  13969. Node.prototype.getClassName = function () {
  13970. return "Node";
  13971. };
  13972. Object.defineProperty(Node.prototype, "onDispose", {
  13973. set: function (callback) {
  13974. if (this._onDisposeObserver) {
  13975. this.onDisposeObservable.remove(this._onDisposeObserver);
  13976. }
  13977. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13978. },
  13979. enumerable: true,
  13980. configurable: true
  13981. });
  13982. Node.prototype.getScene = function () {
  13983. return this._scene;
  13984. };
  13985. Node.prototype.getEngine = function () {
  13986. return this._scene.getEngine();
  13987. };
  13988. Node.prototype.addBehavior = function (behavior) {
  13989. var _this = this;
  13990. var index = this._behaviors.indexOf(behavior);
  13991. if (index !== -1) {
  13992. return this;
  13993. }
  13994. behavior.init();
  13995. if (this._scene.isLoading) {
  13996. // We defer the attach when the scene will be loaded
  13997. var observer = this._scene.onDataLoadedObservable.add(function () {
  13998. behavior.attach(_this);
  13999. setTimeout(function () {
  14000. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14001. _this._scene.onDataLoadedObservable.remove(observer);
  14002. }, 0);
  14003. });
  14004. }
  14005. else {
  14006. behavior.attach(this);
  14007. }
  14008. this._behaviors.push(behavior);
  14009. return this;
  14010. };
  14011. Node.prototype.removeBehavior = function (behavior) {
  14012. var index = this._behaviors.indexOf(behavior);
  14013. if (index === -1) {
  14014. return this;
  14015. }
  14016. this._behaviors[index].detach();
  14017. this._behaviors.splice(index, 1);
  14018. return this;
  14019. };
  14020. Object.defineProperty(Node.prototype, "behaviors", {
  14021. get: function () {
  14022. return this._behaviors;
  14023. },
  14024. enumerable: true,
  14025. configurable: true
  14026. });
  14027. Node.prototype.getBehaviorByName = function (name) {
  14028. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14029. var behavior = _a[_i];
  14030. if (behavior.name === name) {
  14031. return behavior;
  14032. }
  14033. }
  14034. return null;
  14035. };
  14036. // override it in derived class
  14037. Node.prototype.getWorldMatrix = function () {
  14038. return BABYLON.Matrix.Identity();
  14039. };
  14040. // override it in derived class if you add new variables to the cache
  14041. // and call the parent class method
  14042. Node.prototype._initCache = function () {
  14043. this._cache = {};
  14044. this._cache.parent = undefined;
  14045. };
  14046. Node.prototype.updateCache = function (force) {
  14047. if (!force && this.isSynchronized())
  14048. return;
  14049. this._cache.parent = this.parent;
  14050. this._updateCache();
  14051. };
  14052. // override it in derived class if you add new variables to the cache
  14053. // and call the parent class method if !ignoreParentClass
  14054. Node.prototype._updateCache = function (ignoreParentClass) {
  14055. };
  14056. // override it in derived class if you add new variables to the cache
  14057. Node.prototype._isSynchronized = function () {
  14058. return true;
  14059. };
  14060. Node.prototype._markSyncedWithParent = function () {
  14061. if (this.parent) {
  14062. this._parentRenderId = this.parent._currentRenderId;
  14063. }
  14064. };
  14065. Node.prototype.isSynchronizedWithParent = function () {
  14066. if (!this.parent) {
  14067. return true;
  14068. }
  14069. if (this._parentRenderId !== this.parent._currentRenderId) {
  14070. return false;
  14071. }
  14072. return this.parent.isSynchronized();
  14073. };
  14074. Node.prototype.isSynchronized = function (updateCache) {
  14075. var check = this.hasNewParent();
  14076. check = check || !this.isSynchronizedWithParent();
  14077. check = check || !this._isSynchronized();
  14078. if (updateCache)
  14079. this.updateCache(true);
  14080. return !check;
  14081. };
  14082. Node.prototype.hasNewParent = function (update) {
  14083. if (this._cache.parent === this.parent)
  14084. return false;
  14085. if (update)
  14086. this._cache.parent = this.parent;
  14087. return true;
  14088. };
  14089. /**
  14090. * Is this node ready to be used/rendered
  14091. * @return {boolean} is it ready
  14092. */
  14093. Node.prototype.isReady = function () {
  14094. return this._isReady;
  14095. };
  14096. /**
  14097. * Is this node enabled.
  14098. * 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.
  14099. * @param {boolean} [checkAncestors=true] - 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.
  14100. * @return {boolean} whether this node (and its parent) is enabled.
  14101. * @see setEnabled
  14102. */
  14103. Node.prototype.isEnabled = function (checkAncestors) {
  14104. if (checkAncestors === void 0) { checkAncestors = true; }
  14105. if (checkAncestors === false) {
  14106. return this._isEnabled;
  14107. }
  14108. if (this._isEnabled === false) {
  14109. return false;
  14110. }
  14111. if (this.parent !== undefined && this.parent !== null) {
  14112. return this.parent.isEnabled(checkAncestors);
  14113. }
  14114. return true;
  14115. };
  14116. /**
  14117. * Set the enabled state of this node.
  14118. * @param {boolean} value - the new enabled state
  14119. * @see isEnabled
  14120. */
  14121. Node.prototype.setEnabled = function (value) {
  14122. this._isEnabled = value;
  14123. };
  14124. /**
  14125. * Is this node a descendant of the given node.
  14126. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14127. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14128. * @see parent
  14129. */
  14130. Node.prototype.isDescendantOf = function (ancestor) {
  14131. if (this.parent) {
  14132. if (this.parent === ancestor) {
  14133. return true;
  14134. }
  14135. return this.parent.isDescendantOf(ancestor);
  14136. }
  14137. return false;
  14138. };
  14139. /**
  14140. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14141. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14142. * @param {boolean} directDescendantsOnly 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.
  14143. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14144. */
  14145. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14146. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14147. if (!this._children) {
  14148. return;
  14149. }
  14150. for (var index = 0; index < this._children.length; index++) {
  14151. var item = this._children[index];
  14152. if (!predicate || predicate(item)) {
  14153. results.push(item);
  14154. }
  14155. if (!directDescendantsOnly) {
  14156. item._getDescendants(results, false, predicate);
  14157. }
  14158. }
  14159. };
  14160. /**
  14161. * Will return all nodes that have this node as ascendant.
  14162. * @param {boolean} directDescendantsOnly 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.
  14163. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  14164. * @return {BABYLON.Node[]} all children nodes of all types.
  14165. */
  14166. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14167. var results = new Array();
  14168. this._getDescendants(results, directDescendantsOnly, predicate);
  14169. return results;
  14170. };
  14171. /**
  14172. * Get all child-meshes of this node.
  14173. */
  14174. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14175. var results = [];
  14176. this._getDescendants(results, directDescendantsOnly, function (node) {
  14177. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14178. });
  14179. return results;
  14180. };
  14181. /**
  14182. * Get all child-transformNodes of this node.
  14183. */
  14184. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14185. var results = [];
  14186. this._getDescendants(results, directDescendantsOnly, function (node) {
  14187. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14188. });
  14189. return results;
  14190. };
  14191. /**
  14192. * Get all direct children of this node.
  14193. */
  14194. Node.prototype.getChildren = function (predicate) {
  14195. return this.getDescendants(true, predicate);
  14196. };
  14197. Node.prototype._setReady = function (state) {
  14198. if (state === this._isReady) {
  14199. return;
  14200. }
  14201. if (!state) {
  14202. this._isReady = false;
  14203. return;
  14204. }
  14205. this._isReady = true;
  14206. if (this.onReady) {
  14207. this.onReady(this);
  14208. }
  14209. };
  14210. Node.prototype.getAnimationByName = function (name) {
  14211. for (var i = 0; i < this.animations.length; i++) {
  14212. var animation = this.animations[i];
  14213. if (animation.name === name) {
  14214. return animation;
  14215. }
  14216. }
  14217. return null;
  14218. };
  14219. Node.prototype.createAnimationRange = function (name, from, to) {
  14220. // check name not already in use
  14221. if (!this._ranges[name]) {
  14222. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14223. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14224. if (this.animations[i]) {
  14225. this.animations[i].createRange(name, from, to);
  14226. }
  14227. }
  14228. }
  14229. };
  14230. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14231. if (deleteFrames === void 0) { deleteFrames = true; }
  14232. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14233. if (this.animations[i]) {
  14234. this.animations[i].deleteRange(name, deleteFrames);
  14235. }
  14236. }
  14237. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14238. };
  14239. Node.prototype.getAnimationRange = function (name) {
  14240. return this._ranges[name];
  14241. };
  14242. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14243. var range = this.getAnimationRange(name);
  14244. if (!range) {
  14245. return;
  14246. }
  14247. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14248. };
  14249. Node.prototype.serializeAnimationRanges = function () {
  14250. var serializationRanges = [];
  14251. for (var name in this._ranges) {
  14252. var localRange = this._ranges[name];
  14253. if (!localRange) {
  14254. continue;
  14255. }
  14256. var range = {};
  14257. range.name = name;
  14258. range.from = localRange.from;
  14259. range.to = localRange.to;
  14260. serializationRanges.push(range);
  14261. }
  14262. return serializationRanges;
  14263. };
  14264. // override it in derived class
  14265. Node.prototype.computeWorldMatrix = function (force) {
  14266. return BABYLON.Matrix.Identity();
  14267. };
  14268. Node.prototype.dispose = function () {
  14269. this.parent = null;
  14270. // Callback
  14271. this.onDisposeObservable.notifyObservers(this);
  14272. this.onDisposeObservable.clear();
  14273. // Behaviors
  14274. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14275. var behavior = _a[_i];
  14276. behavior.detach();
  14277. }
  14278. this._behaviors = [];
  14279. };
  14280. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14281. if (parsedNode.ranges) {
  14282. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14283. var data = parsedNode.ranges[index];
  14284. node.createAnimationRange(data.name, data.from, data.to);
  14285. }
  14286. }
  14287. };
  14288. __decorate([
  14289. BABYLON.serialize()
  14290. ], Node.prototype, "name", void 0);
  14291. __decorate([
  14292. BABYLON.serialize()
  14293. ], Node.prototype, "id", void 0);
  14294. __decorate([
  14295. BABYLON.serialize()
  14296. ], Node.prototype, "uniqueId", void 0);
  14297. __decorate([
  14298. BABYLON.serialize()
  14299. ], Node.prototype, "state", void 0);
  14300. __decorate([
  14301. BABYLON.serialize()
  14302. ], Node.prototype, "metadata", void 0);
  14303. return Node;
  14304. }());
  14305. BABYLON.Node = Node;
  14306. })(BABYLON || (BABYLON = {}));
  14307. //# sourceMappingURL=babylon.node.js.map
  14308. var BABYLON;
  14309. (function (BABYLON) {
  14310. var BoundingSphere = /** @class */ (function () {
  14311. function BoundingSphere(minimum, maximum) {
  14312. this.minimum = minimum;
  14313. this.maximum = maximum;
  14314. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14315. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14316. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14317. this.radius = distance * 0.5;
  14318. this.centerWorld = BABYLON.Vector3.Zero();
  14319. this._update(BABYLON.Matrix.Identity());
  14320. }
  14321. // Methods
  14322. BoundingSphere.prototype._update = function (world) {
  14323. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14324. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14325. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14326. };
  14327. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14328. for (var i = 0; i < 6; i++) {
  14329. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14330. return false;
  14331. }
  14332. return true;
  14333. };
  14334. BoundingSphere.prototype.intersectsPoint = function (point) {
  14335. var x = this.centerWorld.x - point.x;
  14336. var y = this.centerWorld.y - point.y;
  14337. var z = this.centerWorld.z - point.z;
  14338. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14339. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14340. return false;
  14341. return true;
  14342. };
  14343. // Statics
  14344. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14345. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14346. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14347. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14348. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14349. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14350. return false;
  14351. return true;
  14352. };
  14353. return BoundingSphere;
  14354. }());
  14355. BABYLON.BoundingSphere = BoundingSphere;
  14356. })(BABYLON || (BABYLON = {}));
  14357. //# sourceMappingURL=babylon.boundingSphere.js.map
  14358. var BABYLON;
  14359. (function (BABYLON) {
  14360. var BoundingBox = /** @class */ (function () {
  14361. function BoundingBox(minimum, maximum) {
  14362. this.minimum = minimum;
  14363. this.maximum = maximum;
  14364. this.vectors = new Array();
  14365. this.vectorsWorld = new Array();
  14366. // Bounding vectors
  14367. this.vectors.push(this.minimum.clone());
  14368. this.vectors.push(this.maximum.clone());
  14369. this.vectors.push(this.minimum.clone());
  14370. this.vectors[2].x = this.maximum.x;
  14371. this.vectors.push(this.minimum.clone());
  14372. this.vectors[3].y = this.maximum.y;
  14373. this.vectors.push(this.minimum.clone());
  14374. this.vectors[4].z = this.maximum.z;
  14375. this.vectors.push(this.maximum.clone());
  14376. this.vectors[5].z = this.minimum.z;
  14377. this.vectors.push(this.maximum.clone());
  14378. this.vectors[6].x = this.minimum.x;
  14379. this.vectors.push(this.maximum.clone());
  14380. this.vectors[7].y = this.minimum.y;
  14381. // OBB
  14382. this.center = this.maximum.add(this.minimum).scale(0.5);
  14383. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14384. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14385. // World
  14386. for (var index = 0; index < this.vectors.length; index++) {
  14387. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14388. }
  14389. this.minimumWorld = BABYLON.Vector3.Zero();
  14390. this.maximumWorld = BABYLON.Vector3.Zero();
  14391. this.centerWorld = BABYLON.Vector3.Zero();
  14392. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14393. this._update(BABYLON.Matrix.Identity());
  14394. }
  14395. // Methods
  14396. BoundingBox.prototype.getWorldMatrix = function () {
  14397. return this._worldMatrix;
  14398. };
  14399. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14400. this._worldMatrix.copyFrom(matrix);
  14401. return this;
  14402. };
  14403. BoundingBox.prototype._update = function (world) {
  14404. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14405. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14406. for (var index = 0; index < this.vectors.length; index++) {
  14407. var v = this.vectorsWorld[index];
  14408. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14409. if (v.x < this.minimumWorld.x)
  14410. this.minimumWorld.x = v.x;
  14411. if (v.y < this.minimumWorld.y)
  14412. this.minimumWorld.y = v.y;
  14413. if (v.z < this.minimumWorld.z)
  14414. this.minimumWorld.z = v.z;
  14415. if (v.x > this.maximumWorld.x)
  14416. this.maximumWorld.x = v.x;
  14417. if (v.y > this.maximumWorld.y)
  14418. this.maximumWorld.y = v.y;
  14419. if (v.z > this.maximumWorld.z)
  14420. this.maximumWorld.z = v.z;
  14421. }
  14422. // Extend
  14423. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14424. this.extendSizeWorld.scaleInPlace(0.5);
  14425. // OBB
  14426. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14427. this.centerWorld.scaleInPlace(0.5);
  14428. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14429. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14430. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14431. this._worldMatrix = world;
  14432. };
  14433. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14434. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14435. };
  14436. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14437. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14438. };
  14439. BoundingBox.prototype.intersectsPoint = function (point) {
  14440. var delta = -BABYLON.Epsilon;
  14441. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14442. return false;
  14443. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14444. return false;
  14445. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14446. return false;
  14447. return true;
  14448. };
  14449. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14450. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14451. };
  14452. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14453. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14454. return false;
  14455. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14456. return false;
  14457. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14458. return false;
  14459. return true;
  14460. };
  14461. // Statics
  14462. BoundingBox.Intersects = function (box0, box1) {
  14463. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14464. return false;
  14465. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14466. return false;
  14467. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14468. return false;
  14469. return true;
  14470. };
  14471. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14472. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14473. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14474. return (num <= (sphereRadius * sphereRadius));
  14475. };
  14476. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14477. for (var p = 0; p < 6; p++) {
  14478. for (var i = 0; i < 8; i++) {
  14479. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14480. return false;
  14481. }
  14482. }
  14483. }
  14484. return true;
  14485. };
  14486. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14487. for (var p = 0; p < 6; p++) {
  14488. var inCount = 8;
  14489. for (var i = 0; i < 8; i++) {
  14490. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14491. --inCount;
  14492. }
  14493. else {
  14494. break;
  14495. }
  14496. }
  14497. if (inCount === 0)
  14498. return false;
  14499. }
  14500. return true;
  14501. };
  14502. return BoundingBox;
  14503. }());
  14504. BABYLON.BoundingBox = BoundingBox;
  14505. })(BABYLON || (BABYLON = {}));
  14506. //# sourceMappingURL=babylon.boundingBox.js.map
  14507. var BABYLON;
  14508. (function (BABYLON) {
  14509. var computeBoxExtents = function (axis, box) {
  14510. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14511. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14512. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14513. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14514. var r = r0 + r1 + r2;
  14515. return {
  14516. min: p - r,
  14517. max: p + r
  14518. };
  14519. };
  14520. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14521. var axisOverlap = function (axis, box0, box1) {
  14522. var result0 = computeBoxExtents(axis, box0);
  14523. var result1 = computeBoxExtents(axis, box1);
  14524. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14525. };
  14526. var BoundingInfo = /** @class */ (function () {
  14527. function BoundingInfo(minimum, maximum) {
  14528. this.minimum = minimum;
  14529. this.maximum = maximum;
  14530. this._isLocked = false;
  14531. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14532. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14533. }
  14534. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14535. get: function () {
  14536. return this._isLocked;
  14537. },
  14538. set: function (value) {
  14539. this._isLocked = value;
  14540. },
  14541. enumerable: true,
  14542. configurable: true
  14543. });
  14544. // Methods
  14545. BoundingInfo.prototype.update = function (world) {
  14546. if (this._isLocked) {
  14547. return;
  14548. }
  14549. this.boundingBox._update(world);
  14550. this.boundingSphere._update(world);
  14551. };
  14552. /**
  14553. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14554. * @param center New center of the bounding info
  14555. * @param extend New extend of the bounding info
  14556. */
  14557. BoundingInfo.prototype.centerOn = function (center, extend) {
  14558. this.minimum = center.subtract(extend);
  14559. this.maximum = center.add(extend);
  14560. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14561. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14562. return this;
  14563. };
  14564. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14565. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14566. return false;
  14567. return this.boundingBox.isInFrustum(frustumPlanes);
  14568. };
  14569. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14570. /**
  14571. * Gets the world distance between the min and max points of the bounding box
  14572. */
  14573. get: function () {
  14574. var boundingBox = this.boundingBox;
  14575. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14576. return size.length();
  14577. },
  14578. enumerable: true,
  14579. configurable: true
  14580. });
  14581. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14582. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14583. };
  14584. BoundingInfo.prototype._checkCollision = function (collider) {
  14585. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14586. };
  14587. BoundingInfo.prototype.intersectsPoint = function (point) {
  14588. if (!this.boundingSphere.centerWorld) {
  14589. return false;
  14590. }
  14591. if (!this.boundingSphere.intersectsPoint(point)) {
  14592. return false;
  14593. }
  14594. if (!this.boundingBox.intersectsPoint(point)) {
  14595. return false;
  14596. }
  14597. return true;
  14598. };
  14599. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14600. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14601. return false;
  14602. }
  14603. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14604. return false;
  14605. }
  14606. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14607. return false;
  14608. }
  14609. if (!precise) {
  14610. return true;
  14611. }
  14612. var box0 = this.boundingBox;
  14613. var box1 = boundingInfo.boundingBox;
  14614. if (!axisOverlap(box0.directions[0], box0, box1))
  14615. return false;
  14616. if (!axisOverlap(box0.directions[1], box0, box1))
  14617. return false;
  14618. if (!axisOverlap(box0.directions[2], box0, box1))
  14619. return false;
  14620. if (!axisOverlap(box1.directions[0], box0, box1))
  14621. return false;
  14622. if (!axisOverlap(box1.directions[1], box0, box1))
  14623. return false;
  14624. if (!axisOverlap(box1.directions[2], box0, box1))
  14625. return false;
  14626. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14627. return false;
  14628. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14629. return false;
  14630. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14631. return false;
  14632. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14633. return false;
  14634. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14635. return false;
  14636. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14637. return false;
  14638. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14639. return false;
  14640. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14641. return false;
  14642. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14643. return false;
  14644. return true;
  14645. };
  14646. return BoundingInfo;
  14647. }());
  14648. BABYLON.BoundingInfo = BoundingInfo;
  14649. })(BABYLON || (BABYLON = {}));
  14650. //# sourceMappingURL=babylon.boundingInfo.js.map
  14651. var BABYLON;
  14652. (function (BABYLON) {
  14653. var TransformNode = /** @class */ (function (_super) {
  14654. __extends(TransformNode, _super);
  14655. function TransformNode(name, scene, isPure) {
  14656. if (scene === void 0) { scene = null; }
  14657. if (isPure === void 0) { isPure = true; }
  14658. var _this = _super.call(this, name, scene) || this;
  14659. // Properties
  14660. _this._rotation = BABYLON.Vector3.Zero();
  14661. _this._scaling = BABYLON.Vector3.One();
  14662. _this._isDirty = false;
  14663. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14664. _this.scalingDeterminant = 1;
  14665. _this.infiniteDistance = false;
  14666. _this.position = BABYLON.Vector3.Zero();
  14667. _this._localWorld = BABYLON.Matrix.Zero();
  14668. _this._worldMatrix = BABYLON.Matrix.Zero();
  14669. _this._worldMatrixDeterminant = 0;
  14670. _this._absolutePosition = BABYLON.Vector3.Zero();
  14671. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14672. _this._postMultiplyPivotMatrix = false;
  14673. _this._isWorldMatrixFrozen = false;
  14674. /**
  14675. * An event triggered after the world matrix is updated
  14676. * @type {BABYLON.Observable}
  14677. */
  14678. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14679. _this._nonUniformScaling = false;
  14680. if (isPure) {
  14681. _this.getScene().addTransformNode(_this);
  14682. }
  14683. return _this;
  14684. }
  14685. Object.defineProperty(TransformNode.prototype, "rotation", {
  14686. /**
  14687. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14688. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14689. * Default : (0.0, 0.0, 0.0)
  14690. */
  14691. get: function () {
  14692. return this._rotation;
  14693. },
  14694. set: function (newRotation) {
  14695. this._rotation = newRotation;
  14696. },
  14697. enumerable: true,
  14698. configurable: true
  14699. });
  14700. Object.defineProperty(TransformNode.prototype, "scaling", {
  14701. /**
  14702. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14703. * Default : (1.0, 1.0, 1.0)
  14704. */
  14705. get: function () {
  14706. return this._scaling;
  14707. },
  14708. /**
  14709. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14710. * Default : (1.0, 1.0, 1.0)
  14711. */
  14712. set: function (newScaling) {
  14713. this._scaling = newScaling;
  14714. },
  14715. enumerable: true,
  14716. configurable: true
  14717. });
  14718. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14719. /**
  14720. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14721. * It's null by default.
  14722. * 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)
  14723. */
  14724. get: function () {
  14725. return this._rotationQuaternion;
  14726. },
  14727. set: function (quaternion) {
  14728. this._rotationQuaternion = quaternion;
  14729. //reset the rotation vector.
  14730. if (quaternion && this.rotation.length()) {
  14731. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14732. }
  14733. },
  14734. enumerable: true,
  14735. configurable: true
  14736. });
  14737. /**
  14738. * Returns the latest update of the World matrix
  14739. * Returns a Matrix.
  14740. */
  14741. TransformNode.prototype.getWorldMatrix = function () {
  14742. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14743. this.computeWorldMatrix();
  14744. }
  14745. return this._worldMatrix;
  14746. };
  14747. /**
  14748. * Returns the latest update of the World matrix determinant.
  14749. */
  14750. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14751. return this._worldMatrixDeterminant;
  14752. };
  14753. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14754. /**
  14755. * Returns directly the latest state of the mesh World matrix.
  14756. * A Matrix is returned.
  14757. */
  14758. get: function () {
  14759. return this._worldMatrix;
  14760. },
  14761. enumerable: true,
  14762. configurable: true
  14763. });
  14764. /**
  14765. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14766. * Returns the AbstractMesh.
  14767. */
  14768. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14769. this._poseMatrix.copyFrom(matrix);
  14770. return this;
  14771. };
  14772. /**
  14773. * Returns the mesh Pose matrix.
  14774. * Returned object : Matrix
  14775. */
  14776. TransformNode.prototype.getPoseMatrix = function () {
  14777. return this._poseMatrix;
  14778. };
  14779. TransformNode.prototype._isSynchronized = function () {
  14780. if (this._isDirty) {
  14781. return false;
  14782. }
  14783. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14784. return false;
  14785. if (this._cache.pivotMatrixUpdated) {
  14786. return false;
  14787. }
  14788. if (this.infiniteDistance) {
  14789. return false;
  14790. }
  14791. if (!this._cache.position.equals(this.position))
  14792. return false;
  14793. if (this.rotationQuaternion) {
  14794. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14795. return false;
  14796. }
  14797. if (!this._cache.rotation.equals(this.rotation))
  14798. return false;
  14799. if (!this._cache.scaling.equals(this.scaling))
  14800. return false;
  14801. return true;
  14802. };
  14803. TransformNode.prototype._initCache = function () {
  14804. _super.prototype._initCache.call(this);
  14805. this._cache.localMatrixUpdated = false;
  14806. this._cache.position = BABYLON.Vector3.Zero();
  14807. this._cache.scaling = BABYLON.Vector3.Zero();
  14808. this._cache.rotation = BABYLON.Vector3.Zero();
  14809. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14810. this._cache.billboardMode = -1;
  14811. };
  14812. TransformNode.prototype.markAsDirty = function (property) {
  14813. if (property === "rotation") {
  14814. this.rotationQuaternion = null;
  14815. }
  14816. this._currentRenderId = Number.MAX_VALUE;
  14817. this._isDirty = true;
  14818. return this;
  14819. };
  14820. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14821. /**
  14822. * Returns the current mesh absolute position.
  14823. * Retuns a Vector3.
  14824. */
  14825. get: function () {
  14826. return this._absolutePosition;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. /**
  14832. * Sets a new pivot matrix to the mesh.
  14833. * Returns the AbstractMesh.
  14834. */
  14835. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14836. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14837. this._pivotMatrix = matrix.clone();
  14838. this._cache.pivotMatrixUpdated = true;
  14839. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14840. if (this._postMultiplyPivotMatrix) {
  14841. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14842. }
  14843. return this;
  14844. };
  14845. /**
  14846. * Returns the mesh pivot matrix.
  14847. * Default : Identity.
  14848. * A Matrix is returned.
  14849. */
  14850. TransformNode.prototype.getPivotMatrix = function () {
  14851. return this._pivotMatrix;
  14852. };
  14853. /**
  14854. * Prevents the World matrix to be computed any longer.
  14855. * Returns the AbstractMesh.
  14856. */
  14857. TransformNode.prototype.freezeWorldMatrix = function () {
  14858. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14859. this.computeWorldMatrix(true);
  14860. this._isWorldMatrixFrozen = true;
  14861. return this;
  14862. };
  14863. /**
  14864. * Allows back the World matrix computation.
  14865. * Returns the AbstractMesh.
  14866. */
  14867. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14868. this._isWorldMatrixFrozen = false;
  14869. this.computeWorldMatrix(true);
  14870. return this;
  14871. };
  14872. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14873. /**
  14874. * True if the World matrix has been frozen.
  14875. * Returns a boolean.
  14876. */
  14877. get: function () {
  14878. return this._isWorldMatrixFrozen;
  14879. },
  14880. enumerable: true,
  14881. configurable: true
  14882. });
  14883. /**
  14884. * Retuns the mesh absolute position in the World.
  14885. * Returns a Vector3.
  14886. */
  14887. TransformNode.prototype.getAbsolutePosition = function () {
  14888. this.computeWorldMatrix();
  14889. return this._absolutePosition;
  14890. };
  14891. /**
  14892. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14893. * Returns the AbstractMesh.
  14894. */
  14895. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14896. if (!absolutePosition) {
  14897. return this;
  14898. }
  14899. var absolutePositionX;
  14900. var absolutePositionY;
  14901. var absolutePositionZ;
  14902. if (absolutePosition.x === undefined) {
  14903. if (arguments.length < 3) {
  14904. return this;
  14905. }
  14906. absolutePositionX = arguments[0];
  14907. absolutePositionY = arguments[1];
  14908. absolutePositionZ = arguments[2];
  14909. }
  14910. else {
  14911. absolutePositionX = absolutePosition.x;
  14912. absolutePositionY = absolutePosition.y;
  14913. absolutePositionZ = absolutePosition.z;
  14914. }
  14915. if (this.parent) {
  14916. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14917. invertParentWorldMatrix.invert();
  14918. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14919. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14920. }
  14921. else {
  14922. this.position.x = absolutePositionX;
  14923. this.position.y = absolutePositionY;
  14924. this.position.z = absolutePositionZ;
  14925. }
  14926. return this;
  14927. };
  14928. /**
  14929. * Sets the mesh position in its local space.
  14930. * Returns the AbstractMesh.
  14931. */
  14932. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14933. this.computeWorldMatrix();
  14934. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14935. return this;
  14936. };
  14937. /**
  14938. * Returns the mesh position in the local space from the current World matrix values.
  14939. * Returns a new Vector3.
  14940. */
  14941. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14942. this.computeWorldMatrix();
  14943. var invLocalWorldMatrix = this._localWorld.clone();
  14944. invLocalWorldMatrix.invert();
  14945. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14946. };
  14947. /**
  14948. * Translates the mesh along the passed Vector3 in its local space.
  14949. * Returns the AbstractMesh.
  14950. */
  14951. TransformNode.prototype.locallyTranslate = function (vector3) {
  14952. this.computeWorldMatrix(true);
  14953. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14954. return this;
  14955. };
  14956. /**
  14957. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14958. * @param targetPoint the position (must be in same space as current mesh) to look at
  14959. * @param yawCor optional yaw (y-axis) correction in radians
  14960. * @param pitchCor optional pitch (x-axis) correction in radians
  14961. * @param rollCor optional roll (z-axis) correction in radians
  14962. * @param space the choosen space of the target
  14963. * @returns the TransformNode.
  14964. */
  14965. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14966. if (yawCor === void 0) { yawCor = 0; }
  14967. if (pitchCor === void 0) { pitchCor = 0; }
  14968. if (rollCor === void 0) { rollCor = 0; }
  14969. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14970. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14971. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14972. targetPoint.subtractToRef(pos, dv);
  14973. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14974. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14975. var pitch = Math.atan2(dv.y, len);
  14976. if (this.rotationQuaternion) {
  14977. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14978. }
  14979. else {
  14980. this.rotation.x = pitch + pitchCor;
  14981. this.rotation.y = yaw + yawCor;
  14982. this.rotation.z = rollCor;
  14983. }
  14984. return this;
  14985. };
  14986. /**
  14987. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14988. * This Vector3 is expressed in the World space.
  14989. */
  14990. TransformNode.prototype.getDirection = function (localAxis) {
  14991. var result = BABYLON.Vector3.Zero();
  14992. this.getDirectionToRef(localAxis, result);
  14993. return result;
  14994. };
  14995. /**
  14996. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14997. * localAxis is expressed in the mesh local space.
  14998. * result is computed in the Wordl space from the mesh World matrix.
  14999. * Returns the AbstractMesh.
  15000. */
  15001. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15002. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15003. return this;
  15004. };
  15005. TransformNode.prototype.setPivotPoint = function (point, space) {
  15006. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15007. if (this.getScene().getRenderId() == 0) {
  15008. this.computeWorldMatrix(true);
  15009. }
  15010. var wm = this.getWorldMatrix();
  15011. if (space == BABYLON.Space.WORLD) {
  15012. var tmat = BABYLON.Tmp.Matrix[0];
  15013. wm.invertToRef(tmat);
  15014. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15015. }
  15016. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15017. this._pivotMatrix.m[12] = -point.x;
  15018. this._pivotMatrix.m[13] = -point.y;
  15019. this._pivotMatrix.m[14] = -point.z;
  15020. this._cache.pivotMatrixUpdated = true;
  15021. return this;
  15022. };
  15023. /**
  15024. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15025. */
  15026. TransformNode.prototype.getPivotPoint = function () {
  15027. var point = BABYLON.Vector3.Zero();
  15028. this.getPivotPointToRef(point);
  15029. return point;
  15030. };
  15031. /**
  15032. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15033. * Returns the AbstractMesh.
  15034. */
  15035. TransformNode.prototype.getPivotPointToRef = function (result) {
  15036. result.x = -this._pivotMatrix.m[12];
  15037. result.y = -this._pivotMatrix.m[13];
  15038. result.z = -this._pivotMatrix.m[14];
  15039. return this;
  15040. };
  15041. /**
  15042. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15043. */
  15044. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15045. var point = BABYLON.Vector3.Zero();
  15046. this.getAbsolutePivotPointToRef(point);
  15047. return point;
  15048. };
  15049. /**
  15050. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15051. * Returns the AbstractMesh.
  15052. */
  15053. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15054. result.x = this._pivotMatrix.m[12];
  15055. result.y = this._pivotMatrix.m[13];
  15056. result.z = this._pivotMatrix.m[14];
  15057. this.getPivotPointToRef(result);
  15058. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15059. return this;
  15060. };
  15061. /**
  15062. * Defines the passed node as the parent of the current node.
  15063. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15064. * Returns the TransformNode.
  15065. */
  15066. TransformNode.prototype.setParent = function (node) {
  15067. if (node === null) {
  15068. var rotation = BABYLON.Tmp.Quaternion[0];
  15069. var position = BABYLON.Tmp.Vector3[0];
  15070. var scale = BABYLON.Tmp.Vector3[1];
  15071. if (this.parent && this.parent.computeWorldMatrix) {
  15072. this.parent.computeWorldMatrix(true);
  15073. }
  15074. this.computeWorldMatrix(true);
  15075. this.getWorldMatrix().decompose(scale, rotation, position);
  15076. if (this.rotationQuaternion) {
  15077. this.rotationQuaternion.copyFrom(rotation);
  15078. }
  15079. else {
  15080. rotation.toEulerAnglesToRef(this.rotation);
  15081. }
  15082. this.scaling.x = scale.x;
  15083. this.scaling.y = scale.y;
  15084. this.scaling.z = scale.z;
  15085. this.position.x = position.x;
  15086. this.position.y = position.y;
  15087. this.position.z = position.z;
  15088. }
  15089. else {
  15090. var rotation = BABYLON.Tmp.Quaternion[0];
  15091. var position = BABYLON.Tmp.Vector3[0];
  15092. var scale = BABYLON.Tmp.Vector3[1];
  15093. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15094. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15095. this.computeWorldMatrix(true);
  15096. node.computeWorldMatrix(true);
  15097. node.getWorldMatrix().invertToRef(invParentMatrix);
  15098. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15099. diffMatrix.decompose(scale, rotation, position);
  15100. if (this.rotationQuaternion) {
  15101. this.rotationQuaternion.copyFrom(rotation);
  15102. }
  15103. else {
  15104. rotation.toEulerAnglesToRef(this.rotation);
  15105. }
  15106. this.position.x = position.x;
  15107. this.position.y = position.y;
  15108. this.position.z = position.z;
  15109. this.scaling.x = scale.x;
  15110. this.scaling.y = scale.y;
  15111. this.scaling.z = scale.z;
  15112. }
  15113. this.parent = node;
  15114. return this;
  15115. };
  15116. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15117. get: function () {
  15118. return this._nonUniformScaling;
  15119. },
  15120. enumerable: true,
  15121. configurable: true
  15122. });
  15123. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15124. if (this._nonUniformScaling === value) {
  15125. return false;
  15126. }
  15127. this._nonUniformScaling = true;
  15128. return true;
  15129. };
  15130. /**
  15131. * Attach the current TransformNode to another TransformNode associated with a bone
  15132. * @param bone Bone affecting the TransformNode
  15133. * @param affectedTransformNode TransformNode associated with the bone
  15134. */
  15135. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15136. this._transformToBoneReferal = affectedTransformNode;
  15137. this.parent = bone;
  15138. if (bone.getWorldMatrix().determinant() < 0) {
  15139. this.scalingDeterminant *= -1;
  15140. }
  15141. return this;
  15142. };
  15143. TransformNode.prototype.detachFromBone = function () {
  15144. if (!this.parent) {
  15145. return this;
  15146. }
  15147. if (this.parent.getWorldMatrix().determinant() < 0) {
  15148. this.scalingDeterminant *= -1;
  15149. }
  15150. this._transformToBoneReferal = null;
  15151. this.parent = null;
  15152. return this;
  15153. };
  15154. /**
  15155. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15156. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15157. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15158. * The passed axis is also normalized.
  15159. * Returns the AbstractMesh.
  15160. */
  15161. TransformNode.prototype.rotate = function (axis, amount, space) {
  15162. axis.normalize();
  15163. if (!this.rotationQuaternion) {
  15164. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15165. this.rotation = BABYLON.Vector3.Zero();
  15166. }
  15167. var rotationQuaternion;
  15168. if (!space || space === BABYLON.Space.LOCAL) {
  15169. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15170. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15171. }
  15172. else {
  15173. if (this.parent) {
  15174. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15175. invertParentWorldMatrix.invert();
  15176. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15177. }
  15178. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15179. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15180. }
  15181. return this;
  15182. };
  15183. /**
  15184. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15185. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15186. * The passed axis is also normalized.
  15187. * Returns the AbstractMesh.
  15188. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15189. */
  15190. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15191. axis.normalize();
  15192. if (!this.rotationQuaternion) {
  15193. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15194. this.rotation.copyFromFloats(0, 0, 0);
  15195. }
  15196. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15197. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15198. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15199. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15200. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15201. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15202. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15203. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15204. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15205. return this;
  15206. };
  15207. /**
  15208. * Translates the mesh along the axis vector for the passed distance in the given space.
  15209. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15210. * Returns the AbstractMesh.
  15211. */
  15212. TransformNode.prototype.translate = function (axis, distance, space) {
  15213. var displacementVector = axis.scale(distance);
  15214. if (!space || space === BABYLON.Space.LOCAL) {
  15215. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15216. this.setPositionWithLocalVector(tempV3);
  15217. }
  15218. else {
  15219. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15220. }
  15221. return this;
  15222. };
  15223. /**
  15224. * Adds a rotation step to the mesh current rotation.
  15225. * x, y, z are Euler angles expressed in radians.
  15226. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15227. * This means this rotation is made in the mesh local space only.
  15228. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15229. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15230. * ```javascript
  15231. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15232. * ```
  15233. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15234. * 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.
  15235. * Returns the AbstractMesh.
  15236. */
  15237. TransformNode.prototype.addRotation = function (x, y, z) {
  15238. var rotationQuaternion;
  15239. if (this.rotationQuaternion) {
  15240. rotationQuaternion = this.rotationQuaternion;
  15241. }
  15242. else {
  15243. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15244. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15245. }
  15246. var accumulation = BABYLON.Tmp.Quaternion[0];
  15247. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15248. rotationQuaternion.multiplyInPlace(accumulation);
  15249. if (!this.rotationQuaternion) {
  15250. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15251. }
  15252. return this;
  15253. };
  15254. /**
  15255. * Computes the mesh World matrix and returns it.
  15256. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15257. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15258. * If the parameter `force`is set to `true`, the actual computation is done.
  15259. * Returns the mesh World Matrix.
  15260. */
  15261. TransformNode.prototype.computeWorldMatrix = function (force) {
  15262. if (this._isWorldMatrixFrozen) {
  15263. return this._worldMatrix;
  15264. }
  15265. if (!force && this.isSynchronized(true)) {
  15266. return this._worldMatrix;
  15267. }
  15268. this._cache.position.copyFrom(this.position);
  15269. this._cache.scaling.copyFrom(this.scaling);
  15270. this._cache.pivotMatrixUpdated = false;
  15271. this._cache.billboardMode = this.billboardMode;
  15272. this._currentRenderId = this.getScene().getRenderId();
  15273. this._isDirty = false;
  15274. // Scaling
  15275. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15276. // Rotation
  15277. //rotate, if quaternion is set and rotation was used
  15278. if (this.rotationQuaternion) {
  15279. var len = this.rotation.length();
  15280. if (len) {
  15281. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15282. this.rotation.copyFromFloats(0, 0, 0);
  15283. }
  15284. }
  15285. if (this.rotationQuaternion) {
  15286. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15287. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15288. }
  15289. else {
  15290. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15291. this._cache.rotation.copyFrom(this.rotation);
  15292. }
  15293. // Translation
  15294. var camera = this.getScene().activeCamera;
  15295. if (this.infiniteDistance && !this.parent && camera) {
  15296. var cameraWorldMatrix = camera.getWorldMatrix();
  15297. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15298. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15299. }
  15300. else {
  15301. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15302. }
  15303. // Composing transformations
  15304. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15305. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15306. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15307. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15308. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15309. // Need to decompose each rotation here
  15310. var currentPosition = BABYLON.Tmp.Vector3[3];
  15311. if (this.parent && this.parent.getWorldMatrix) {
  15312. if (this._transformToBoneReferal) {
  15313. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15314. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15315. }
  15316. else {
  15317. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15318. }
  15319. }
  15320. else {
  15321. currentPosition.copyFrom(this.position);
  15322. }
  15323. currentPosition.subtractInPlace(camera.globalPosition);
  15324. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15325. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15326. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15327. }
  15328. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15329. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15330. }
  15331. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15332. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15333. }
  15334. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15335. }
  15336. else {
  15337. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15338. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15339. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15340. }
  15341. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15342. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15343. }
  15344. // Local world
  15345. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15346. // Parent
  15347. if (this.parent && this.parent.getWorldMatrix) {
  15348. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15349. if (this._transformToBoneReferal) {
  15350. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15351. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15352. }
  15353. else {
  15354. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15355. }
  15356. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15357. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15358. this._worldMatrix.copyFrom(this._localWorld);
  15359. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15360. }
  15361. else {
  15362. if (this._transformToBoneReferal) {
  15363. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15364. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15365. }
  15366. else {
  15367. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15368. }
  15369. }
  15370. this._markSyncedWithParent();
  15371. }
  15372. else {
  15373. this._worldMatrix.copyFrom(this._localWorld);
  15374. }
  15375. // Post multiply inverse of pivotMatrix
  15376. if (this._postMultiplyPivotMatrix) {
  15377. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15378. }
  15379. // Normal matrix
  15380. if (this.scaling.isNonUniform) {
  15381. this._updateNonUniformScalingState(true);
  15382. }
  15383. else if (this.parent && this.parent._nonUniformScaling) {
  15384. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15385. }
  15386. else {
  15387. this._updateNonUniformScalingState(false);
  15388. }
  15389. this._afterComputeWorldMatrix();
  15390. // Absolute position
  15391. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15392. // Callbacks
  15393. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15394. if (!this._poseMatrix) {
  15395. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15396. }
  15397. // Cache the determinant
  15398. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15399. return this._worldMatrix;
  15400. };
  15401. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15402. };
  15403. /**
  15404. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15405. * @param func: callback function to add
  15406. *
  15407. * Returns the TransformNode.
  15408. */
  15409. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15410. this.onAfterWorldMatrixUpdateObservable.add(func);
  15411. return this;
  15412. };
  15413. /**
  15414. * Removes a registered callback function.
  15415. * Returns the TransformNode.
  15416. */
  15417. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15418. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15419. return this;
  15420. };
  15421. /**
  15422. * Clone the current transform node
  15423. * Returns the new transform node
  15424. * @param name Name of the new clone
  15425. * @param newParent New parent for the clone
  15426. * @param doNotCloneChildren Do not clone children hierarchy
  15427. */
  15428. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15429. var _this = this;
  15430. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15431. result.name = name;
  15432. result.id = name;
  15433. if (newParent) {
  15434. result.parent = newParent;
  15435. }
  15436. if (!doNotCloneChildren) {
  15437. // Children
  15438. var directDescendants = this.getDescendants(true);
  15439. for (var index = 0; index < directDescendants.length; index++) {
  15440. var child = directDescendants[index];
  15441. if (child.clone) {
  15442. child.clone(name + "." + child.name, result);
  15443. }
  15444. }
  15445. }
  15446. return result;
  15447. };
  15448. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15449. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15450. serializationObject.type = this.getClassName();
  15451. // Parent
  15452. if (this.parent) {
  15453. serializationObject.parentId = this.parent.id;
  15454. }
  15455. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15456. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15457. }
  15458. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15459. serializationObject.isEnabled = this.isEnabled();
  15460. // Parent
  15461. if (this.parent) {
  15462. serializationObject.parentId = this.parent.id;
  15463. }
  15464. return serializationObject;
  15465. };
  15466. // Statics
  15467. /**
  15468. * Returns a new TransformNode object parsed from the source provided.
  15469. * The parameter `parsedMesh` is the source.
  15470. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15471. */
  15472. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15473. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15474. if (BABYLON.Tags) {
  15475. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15476. }
  15477. if (parsedTransformNode.localMatrix) {
  15478. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15479. }
  15480. else if (parsedTransformNode.pivotMatrix) {
  15481. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15482. }
  15483. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15484. // Parent
  15485. if (parsedTransformNode.parentId) {
  15486. transformNode._waitingParentId = parsedTransformNode.parentId;
  15487. }
  15488. return transformNode;
  15489. };
  15490. /**
  15491. * Disposes the TransformNode.
  15492. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15493. * Returns nothing.
  15494. */
  15495. TransformNode.prototype.dispose = function (doNotRecurse) {
  15496. // Animations
  15497. this.getScene().stopAnimation(this);
  15498. // Remove from scene
  15499. this.getScene().removeTransformNode(this);
  15500. if (!doNotRecurse) {
  15501. // Children
  15502. var objects = this.getDescendants(true);
  15503. for (var index = 0; index < objects.length; index++) {
  15504. objects[index].dispose();
  15505. }
  15506. }
  15507. else {
  15508. var childMeshes = this.getChildMeshes(true);
  15509. for (index = 0; index < childMeshes.length; index++) {
  15510. var child = childMeshes[index];
  15511. child.parent = null;
  15512. child.computeWorldMatrix(true);
  15513. }
  15514. }
  15515. this.onAfterWorldMatrixUpdateObservable.clear();
  15516. _super.prototype.dispose.call(this);
  15517. };
  15518. // Statics
  15519. TransformNode.BILLBOARDMODE_NONE = 0;
  15520. TransformNode.BILLBOARDMODE_X = 1;
  15521. TransformNode.BILLBOARDMODE_Y = 2;
  15522. TransformNode.BILLBOARDMODE_Z = 4;
  15523. TransformNode.BILLBOARDMODE_ALL = 7;
  15524. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15525. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15526. __decorate([
  15527. BABYLON.serializeAsVector3()
  15528. ], TransformNode.prototype, "_rotation", void 0);
  15529. __decorate([
  15530. BABYLON.serializeAsQuaternion()
  15531. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15532. __decorate([
  15533. BABYLON.serializeAsVector3()
  15534. ], TransformNode.prototype, "_scaling", void 0);
  15535. __decorate([
  15536. BABYLON.serialize()
  15537. ], TransformNode.prototype, "billboardMode", void 0);
  15538. __decorate([
  15539. BABYLON.serialize()
  15540. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15541. __decorate([
  15542. BABYLON.serialize()
  15543. ], TransformNode.prototype, "infiniteDistance", void 0);
  15544. __decorate([
  15545. BABYLON.serializeAsVector3()
  15546. ], TransformNode.prototype, "position", void 0);
  15547. return TransformNode;
  15548. }(BABYLON.Node));
  15549. BABYLON.TransformNode = TransformNode;
  15550. })(BABYLON || (BABYLON = {}));
  15551. //# sourceMappingURL=babylon.transformNode.js.map
  15552. var BABYLON;
  15553. (function (BABYLON) {
  15554. var AbstractMesh = /** @class */ (function (_super) {
  15555. __extends(AbstractMesh, _super);
  15556. // Constructor
  15557. function AbstractMesh(name, scene) {
  15558. if (scene === void 0) { scene = null; }
  15559. var _this = _super.call(this, name, scene, false) || this;
  15560. _this._facetNb = 0; // facet number
  15561. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15562. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15563. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15564. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15565. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15566. _this._subDiv = {
  15567. max: 1,
  15568. X: 1,
  15569. Y: 1,
  15570. Z: 1
  15571. };
  15572. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15573. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15574. // Events
  15575. /**
  15576. * An event triggered when this mesh collides with another one
  15577. * @type {BABYLON.Observable}
  15578. */
  15579. _this.onCollideObservable = new BABYLON.Observable();
  15580. /**
  15581. * An event triggered when the collision's position changes
  15582. * @type {BABYLON.Observable}
  15583. */
  15584. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15585. /**
  15586. * An event triggered when material is changed
  15587. * @type {BABYLON.Observable}
  15588. */
  15589. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15590. // Properties
  15591. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15592. /**
  15593. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15594. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15595. * or
  15596. * 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.
  15597. * for more info check WebGl documentations
  15598. */
  15599. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15600. /**
  15601. * 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:
  15602. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15603. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15604. * 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.
  15605. */
  15606. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15607. /**
  15608. * 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.
  15609. * The default value is -1 which means don't break the query and wait till the result.
  15610. */
  15611. _this.occlusionRetryCount = -1;
  15612. _this._occlusionInternalRetryCounter = 0;
  15613. _this._isOccluded = false;
  15614. _this._isOcclusionQueryInProgress = false;
  15615. _this.visibility = 1.0;
  15616. _this.alphaIndex = Number.MAX_VALUE;
  15617. _this.isVisible = true;
  15618. _this.isPickable = true;
  15619. _this.showBoundingBox = false;
  15620. _this.showSubMeshesBoundingBox = false;
  15621. _this.isBlocker = false;
  15622. _this.enablePointerMoveEvents = false;
  15623. _this.renderingGroupId = 0;
  15624. _this._receiveShadows = false;
  15625. _this.renderOutline = false;
  15626. _this.outlineColor = BABYLON.Color3.Red();
  15627. _this.outlineWidth = 0.02;
  15628. _this.renderOverlay = false;
  15629. _this.overlayColor = BABYLON.Color3.Red();
  15630. _this.overlayAlpha = 0.5;
  15631. _this._hasVertexAlpha = false;
  15632. _this._useVertexColors = true;
  15633. _this._computeBonesUsingShaders = true;
  15634. _this._numBoneInfluencers = 4;
  15635. _this._applyFog = true;
  15636. _this.useOctreeForRenderingSelection = true;
  15637. _this.useOctreeForPicking = true;
  15638. _this.useOctreeForCollisions = true;
  15639. _this._layerMask = 0x0FFFFFFF;
  15640. /**
  15641. * True if the mesh must be rendered in any case.
  15642. */
  15643. _this.alwaysSelectAsActiveMesh = false;
  15644. /**
  15645. * This scene's action manager
  15646. * @type {BABYLON.ActionManager}
  15647. */
  15648. _this.actionManager = null;
  15649. // Physics
  15650. _this.physicsImpostor = null;
  15651. // Collisions
  15652. _this._checkCollisions = false;
  15653. _this._collisionMask = -1;
  15654. _this._collisionGroup = -1;
  15655. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15656. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15657. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15658. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15659. // Edges
  15660. _this.edgesWidth = 1;
  15661. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15662. // Cache
  15663. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15664. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15665. _this._isDisposed = false;
  15666. _this._renderId = 0;
  15667. _this._intersectionsInProgress = new Array();
  15668. _this._unIndexed = false;
  15669. _this._lightSources = new Array();
  15670. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15671. if (collidedMesh === void 0) { collidedMesh = null; }
  15672. //TODO move this to the collision coordinator!
  15673. if (_this.getScene().workerCollisions)
  15674. newPosition.multiplyInPlace(_this._collider._radius);
  15675. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15676. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15677. _this.position.addInPlace(_this._diffPositionForCollisions);
  15678. }
  15679. if (collidedMesh) {
  15680. _this.onCollideObservable.notifyObservers(collidedMesh);
  15681. }
  15682. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15683. };
  15684. _this.getScene().addMesh(_this);
  15685. _this._resyncLightSources();
  15686. return _this;
  15687. }
  15688. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15689. get: function () {
  15690. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15691. },
  15692. enumerable: true,
  15693. configurable: true
  15694. });
  15695. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15696. get: function () {
  15697. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15698. },
  15699. enumerable: true,
  15700. configurable: true
  15701. });
  15702. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15703. get: function () {
  15704. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15710. get: function () {
  15711. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15712. },
  15713. enumerable: true,
  15714. configurable: true
  15715. });
  15716. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15717. get: function () {
  15718. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15719. },
  15720. enumerable: true,
  15721. configurable: true
  15722. });
  15723. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15724. /**
  15725. * Read-only : the number of facets in the mesh
  15726. */
  15727. get: function () {
  15728. return this._facetNb;
  15729. },
  15730. enumerable: true,
  15731. configurable: true
  15732. });
  15733. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15734. /**
  15735. * The number (integer) of subdivisions per axis in the partioning space
  15736. */
  15737. get: function () {
  15738. return this._partitioningSubdivisions;
  15739. },
  15740. set: function (nb) {
  15741. this._partitioningSubdivisions = nb;
  15742. },
  15743. enumerable: true,
  15744. configurable: true
  15745. });
  15746. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15747. /**
  15748. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15749. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15750. */
  15751. get: function () {
  15752. return this._partitioningBBoxRatio;
  15753. },
  15754. set: function (ratio) {
  15755. this._partitioningBBoxRatio = ratio;
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15761. /**
  15762. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15763. * Works only for updatable meshes.
  15764. * Doesn't work with multi-materials.
  15765. */
  15766. get: function () {
  15767. return this._facetDepthSort;
  15768. },
  15769. set: function (sort) {
  15770. this._facetDepthSort = sort;
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15776. /**
  15777. * The location (Vector3) where the facet depth sort must be computed from.
  15778. * By default, the active camera position.
  15779. * Used only when facet depth sort is enabled.
  15780. */
  15781. get: function () {
  15782. return this._facetDepthSortFrom;
  15783. },
  15784. set: function (location) {
  15785. this._facetDepthSortFrom = location;
  15786. },
  15787. enumerable: true,
  15788. configurable: true
  15789. });
  15790. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15791. /**
  15792. * Read-only boolean : is the feature facetData enabled ?
  15793. */
  15794. get: function () {
  15795. return this._facetDataEnabled;
  15796. },
  15797. enumerable: true,
  15798. configurable: true
  15799. });
  15800. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15801. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15802. return false;
  15803. }
  15804. this._markSubMeshesAsMiscDirty();
  15805. return true;
  15806. };
  15807. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15808. set: function (callback) {
  15809. if (this._onCollideObserver) {
  15810. this.onCollideObservable.remove(this._onCollideObserver);
  15811. }
  15812. this._onCollideObserver = this.onCollideObservable.add(callback);
  15813. },
  15814. enumerable: true,
  15815. configurable: true
  15816. });
  15817. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15818. set: function (callback) {
  15819. if (this._onCollisionPositionChangeObserver) {
  15820. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15821. }
  15822. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15823. },
  15824. enumerable: true,
  15825. configurable: true
  15826. });
  15827. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15828. /**
  15829. * Property isOccluded : 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.
  15830. */
  15831. get: function () {
  15832. return this._isOccluded;
  15833. },
  15834. set: function (value) {
  15835. this._isOccluded = value;
  15836. },
  15837. enumerable: true,
  15838. configurable: true
  15839. });
  15840. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15841. /**
  15842. * Flag to check the progress status of the query
  15843. */
  15844. get: function () {
  15845. return this._isOcclusionQueryInProgress;
  15846. },
  15847. enumerable: true,
  15848. configurable: true
  15849. });
  15850. Object.defineProperty(AbstractMesh.prototype, "material", {
  15851. get: function () {
  15852. return this._material;
  15853. },
  15854. set: function (value) {
  15855. if (this._material === value) {
  15856. return;
  15857. }
  15858. this._material = value;
  15859. if (this.onMaterialChangedObservable.hasObservers) {
  15860. this.onMaterialChangedObservable.notifyObservers(this);
  15861. }
  15862. if (!this.subMeshes) {
  15863. return;
  15864. }
  15865. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15866. var subMesh = _a[_i];
  15867. subMesh.setEffect(null);
  15868. }
  15869. },
  15870. enumerable: true,
  15871. configurable: true
  15872. });
  15873. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15874. get: function () {
  15875. return this._receiveShadows;
  15876. },
  15877. set: function (value) {
  15878. if (this._receiveShadows === value) {
  15879. return;
  15880. }
  15881. this._receiveShadows = value;
  15882. this._markSubMeshesAsLightDirty();
  15883. },
  15884. enumerable: true,
  15885. configurable: true
  15886. });
  15887. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15888. get: function () {
  15889. return this._hasVertexAlpha;
  15890. },
  15891. set: function (value) {
  15892. if (this._hasVertexAlpha === value) {
  15893. return;
  15894. }
  15895. this._hasVertexAlpha = value;
  15896. this._markSubMeshesAsAttributesDirty();
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15902. get: function () {
  15903. return this._useVertexColors;
  15904. },
  15905. set: function (value) {
  15906. if (this._useVertexColors === value) {
  15907. return;
  15908. }
  15909. this._useVertexColors = value;
  15910. this._markSubMeshesAsAttributesDirty();
  15911. },
  15912. enumerable: true,
  15913. configurable: true
  15914. });
  15915. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15916. get: function () {
  15917. return this._computeBonesUsingShaders;
  15918. },
  15919. set: function (value) {
  15920. if (this._computeBonesUsingShaders === value) {
  15921. return;
  15922. }
  15923. this._computeBonesUsingShaders = value;
  15924. this._markSubMeshesAsAttributesDirty();
  15925. },
  15926. enumerable: true,
  15927. configurable: true
  15928. });
  15929. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15930. get: function () {
  15931. return this._numBoneInfluencers;
  15932. },
  15933. set: function (value) {
  15934. if (this._numBoneInfluencers === value) {
  15935. return;
  15936. }
  15937. this._numBoneInfluencers = value;
  15938. this._markSubMeshesAsAttributesDirty();
  15939. },
  15940. enumerable: true,
  15941. configurable: true
  15942. });
  15943. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15944. get: function () {
  15945. return this._applyFog;
  15946. },
  15947. set: function (value) {
  15948. if (this._applyFog === value) {
  15949. return;
  15950. }
  15951. this._applyFog = value;
  15952. this._markSubMeshesAsMiscDirty();
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15958. get: function () {
  15959. return this._layerMask;
  15960. },
  15961. set: function (value) {
  15962. if (value === this._layerMask) {
  15963. return;
  15964. }
  15965. this._layerMask = value;
  15966. this._resyncLightSources();
  15967. },
  15968. enumerable: true,
  15969. configurable: true
  15970. });
  15971. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15972. get: function () {
  15973. return this._collisionMask;
  15974. },
  15975. set: function (mask) {
  15976. this._collisionMask = !isNaN(mask) ? mask : -1;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15982. get: function () {
  15983. return this._collisionGroup;
  15984. },
  15985. set: function (mask) {
  15986. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15987. },
  15988. enumerable: true,
  15989. configurable: true
  15990. });
  15991. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15992. get: function () {
  15993. return null;
  15994. },
  15995. enumerable: true,
  15996. configurable: true
  15997. });
  15998. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15999. get: function () {
  16000. return this._skeleton;
  16001. },
  16002. set: function (value) {
  16003. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16004. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16005. }
  16006. if (value && value.needInitialSkinMatrix) {
  16007. value._registerMeshWithPoseMatrix(this);
  16008. }
  16009. this._skeleton = value;
  16010. if (!this._skeleton) {
  16011. this._bonesTransformMatrices = null;
  16012. }
  16013. this._markSubMeshesAsAttributesDirty();
  16014. },
  16015. enumerable: true,
  16016. configurable: true
  16017. });
  16018. /**
  16019. * Boolean : true if the mesh has been disposed.
  16020. */
  16021. AbstractMesh.prototype.isDisposed = function () {
  16022. return this._isDisposed;
  16023. };
  16024. /**
  16025. * Returns the string "AbstractMesh"
  16026. */
  16027. AbstractMesh.prototype.getClassName = function () {
  16028. return "AbstractMesh";
  16029. };
  16030. /**
  16031. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16032. */
  16033. AbstractMesh.prototype.toString = function (fullDetails) {
  16034. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16035. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16036. if (this._skeleton) {
  16037. ret += ", skeleton: " + this._skeleton.name;
  16038. }
  16039. if (fullDetails) {
  16040. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16041. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16042. }
  16043. return ret;
  16044. };
  16045. AbstractMesh.prototype._rebuild = function () {
  16046. if (this._occlusionQuery) {
  16047. this._occlusionQuery = null;
  16048. }
  16049. if (this._edgesRenderer) {
  16050. this._edgesRenderer._rebuild();
  16051. }
  16052. if (!this.subMeshes) {
  16053. return;
  16054. }
  16055. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16056. var subMesh = _a[_i];
  16057. subMesh._rebuild();
  16058. }
  16059. };
  16060. AbstractMesh.prototype._resyncLightSources = function () {
  16061. this._lightSources.length = 0;
  16062. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16063. var light = _a[_i];
  16064. if (!light.isEnabled()) {
  16065. continue;
  16066. }
  16067. if (light.canAffectMesh(this)) {
  16068. this._lightSources.push(light);
  16069. }
  16070. }
  16071. this._markSubMeshesAsLightDirty();
  16072. };
  16073. AbstractMesh.prototype._resyncLighSource = function (light) {
  16074. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16075. var index = this._lightSources.indexOf(light);
  16076. if (index === -1) {
  16077. if (!isIn) {
  16078. return;
  16079. }
  16080. this._lightSources.push(light);
  16081. }
  16082. else {
  16083. if (isIn) {
  16084. return;
  16085. }
  16086. this._lightSources.splice(index, 1);
  16087. }
  16088. this._markSubMeshesAsLightDirty();
  16089. };
  16090. AbstractMesh.prototype._removeLightSource = function (light) {
  16091. var index = this._lightSources.indexOf(light);
  16092. if (index === -1) {
  16093. return;
  16094. }
  16095. this._lightSources.splice(index, 1);
  16096. this._markSubMeshesAsLightDirty();
  16097. };
  16098. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16099. if (!this.subMeshes) {
  16100. return;
  16101. }
  16102. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16103. var subMesh = _a[_i];
  16104. if (subMesh._materialDefines) {
  16105. func(subMesh._materialDefines);
  16106. }
  16107. }
  16108. };
  16109. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16110. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16111. };
  16112. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16113. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16114. };
  16115. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16116. if (!this.subMeshes) {
  16117. return;
  16118. }
  16119. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16120. var subMesh = _a[_i];
  16121. var material = subMesh.getMaterial();
  16122. if (material) {
  16123. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16124. }
  16125. }
  16126. };
  16127. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16128. /**
  16129. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16130. * Default : (1.0, 1.0, 1.0)
  16131. */
  16132. get: function () {
  16133. return this._scaling;
  16134. },
  16135. /**
  16136. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16137. * Default : (1.0, 1.0, 1.0)
  16138. */
  16139. set: function (newScaling) {
  16140. this._scaling = newScaling;
  16141. if (this.physicsImpostor) {
  16142. this.physicsImpostor.forceUpdate();
  16143. }
  16144. },
  16145. enumerable: true,
  16146. configurable: true
  16147. });
  16148. // Methods
  16149. /**
  16150. * Disables the mesh edger rendering mode.
  16151. * Returns the AbstractMesh.
  16152. */
  16153. AbstractMesh.prototype.disableEdgesRendering = function () {
  16154. if (this._edgesRenderer) {
  16155. this._edgesRenderer.dispose();
  16156. this._edgesRenderer = null;
  16157. }
  16158. return this;
  16159. };
  16160. /**
  16161. * Enables the edge rendering mode on the mesh.
  16162. * This mode makes the mesh edges visible.
  16163. * Returns the AbstractMesh.
  16164. */
  16165. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16166. if (epsilon === void 0) { epsilon = 0.95; }
  16167. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16168. this.disableEdgesRendering();
  16169. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16170. return this;
  16171. };
  16172. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16173. /**
  16174. * Returns true if the mesh is blocked. Used by the class Mesh.
  16175. * Returns the boolean `false` by default.
  16176. */
  16177. get: function () {
  16178. return false;
  16179. },
  16180. enumerable: true,
  16181. configurable: true
  16182. });
  16183. /**
  16184. * Returns the mesh itself by default, used by the class Mesh.
  16185. * Returned type : AbstractMesh
  16186. */
  16187. AbstractMesh.prototype.getLOD = function (camera) {
  16188. return this;
  16189. };
  16190. /**
  16191. * Returns 0 by default, used by the class Mesh.
  16192. * Returns an integer.
  16193. */
  16194. AbstractMesh.prototype.getTotalVertices = function () {
  16195. return 0;
  16196. };
  16197. /**
  16198. * Returns null by default, used by the class Mesh.
  16199. * Returned type : integer array
  16200. */
  16201. AbstractMesh.prototype.getIndices = function () {
  16202. return null;
  16203. };
  16204. /**
  16205. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16206. * Returned type : float array or Float32Array
  16207. */
  16208. AbstractMesh.prototype.getVerticesData = function (kind) {
  16209. return null;
  16210. };
  16211. /**
  16212. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16213. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16214. * The `data` are either a numeric array either a Float32Array.
  16215. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16216. * 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).
  16217. * Note that a new underlying VertexBuffer object is created each call.
  16218. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16219. *
  16220. * Possible `kind` values :
  16221. * - BABYLON.VertexBuffer.PositionKind
  16222. * - BABYLON.VertexBuffer.UVKind
  16223. * - BABYLON.VertexBuffer.UV2Kind
  16224. * - BABYLON.VertexBuffer.UV3Kind
  16225. * - BABYLON.VertexBuffer.UV4Kind
  16226. * - BABYLON.VertexBuffer.UV5Kind
  16227. * - BABYLON.VertexBuffer.UV6Kind
  16228. * - BABYLON.VertexBuffer.ColorKind
  16229. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16230. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16231. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16232. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16233. *
  16234. * Returns the Mesh.
  16235. */
  16236. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16237. return this;
  16238. };
  16239. /**
  16240. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16241. * If the mesh has no geometry, it is simply returned as it is.
  16242. * The `data` are either a numeric array either a Float32Array.
  16243. * No new underlying VertexBuffer object is created.
  16244. * 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.
  16245. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16246. *
  16247. * Possible `kind` values :
  16248. * - BABYLON.VertexBuffer.PositionKind
  16249. * - BABYLON.VertexBuffer.UVKind
  16250. * - BABYLON.VertexBuffer.UV2Kind
  16251. * - BABYLON.VertexBuffer.UV3Kind
  16252. * - BABYLON.VertexBuffer.UV4Kind
  16253. * - BABYLON.VertexBuffer.UV5Kind
  16254. * - BABYLON.VertexBuffer.UV6Kind
  16255. * - BABYLON.VertexBuffer.ColorKind
  16256. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16257. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16258. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16259. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16260. *
  16261. * Returns the Mesh.
  16262. */
  16263. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16264. return this;
  16265. };
  16266. /**
  16267. * Sets the mesh indices.
  16268. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16269. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16270. * This method creates a new index buffer each call.
  16271. * Returns the Mesh.
  16272. */
  16273. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16274. return this;
  16275. };
  16276. /** Returns false by default, used by the class Mesh.
  16277. * Returns a boolean
  16278. */
  16279. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16280. return false;
  16281. };
  16282. /**
  16283. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16284. * Returns a BoundingInfo
  16285. */
  16286. AbstractMesh.prototype.getBoundingInfo = function () {
  16287. if (this._masterMesh) {
  16288. return this._masterMesh.getBoundingInfo();
  16289. }
  16290. if (!this._boundingInfo) {
  16291. // this._boundingInfo is being created here
  16292. this._updateBoundingInfo();
  16293. }
  16294. // cannot be null.
  16295. return this._boundingInfo;
  16296. };
  16297. /**
  16298. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16299. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16300. */
  16301. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16302. if (includeDescendants === void 0) { includeDescendants = true; }
  16303. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16304. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16305. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16306. if (maxDimension === 0) {
  16307. return this;
  16308. }
  16309. var scale = 1 / maxDimension;
  16310. this.scaling.scaleInPlace(scale);
  16311. return this;
  16312. };
  16313. /**
  16314. * Sets a mesh new object BoundingInfo.
  16315. * Returns the AbstractMesh.
  16316. */
  16317. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16318. this._boundingInfo = boundingInfo;
  16319. return this;
  16320. };
  16321. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16322. get: function () {
  16323. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16324. },
  16325. enumerable: true,
  16326. configurable: true
  16327. });
  16328. AbstractMesh.prototype._preActivate = function () {
  16329. };
  16330. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16331. };
  16332. AbstractMesh.prototype._activate = function (renderId) {
  16333. this._renderId = renderId;
  16334. };
  16335. /**
  16336. * Returns the latest update of the World matrix
  16337. * Returns a Matrix.
  16338. */
  16339. AbstractMesh.prototype.getWorldMatrix = function () {
  16340. if (this._masterMesh) {
  16341. return this._masterMesh.getWorldMatrix();
  16342. }
  16343. return _super.prototype.getWorldMatrix.call(this);
  16344. };
  16345. /**
  16346. * Returns the latest update of the World matrix determinant.
  16347. */
  16348. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16349. if (this._masterMesh) {
  16350. return this._masterMesh._getWorldMatrixDeterminant();
  16351. }
  16352. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16353. };
  16354. // ================================== Point of View Movement =================================
  16355. /**
  16356. * Perform relative position change from the point of view of behind the front of the mesh.
  16357. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16358. * Supports definition of mesh facing forward or backward.
  16359. * @param {number} amountRight
  16360. * @param {number} amountUp
  16361. * @param {number} amountForward
  16362. *
  16363. * Returns the AbstractMesh.
  16364. */
  16365. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16366. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16367. return this;
  16368. };
  16369. /**
  16370. * Calculate relative position change from the point of view of behind the front of the mesh.
  16371. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16372. * Supports definition of mesh facing forward or backward.
  16373. * @param {number} amountRight
  16374. * @param {number} amountUp
  16375. * @param {number} amountForward
  16376. *
  16377. * Returns a new Vector3.
  16378. */
  16379. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16380. var rotMatrix = new BABYLON.Matrix();
  16381. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16382. rotQuaternion.toRotationMatrix(rotMatrix);
  16383. var translationDelta = BABYLON.Vector3.Zero();
  16384. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16385. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16386. return translationDelta;
  16387. };
  16388. // ================================== Point of View Rotation =================================
  16389. /**
  16390. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16391. * Supports definition of mesh facing forward or backward.
  16392. * @param {number} flipBack
  16393. * @param {number} twirlClockwise
  16394. * @param {number} tiltRight
  16395. *
  16396. * Returns the AbstractMesh.
  16397. */
  16398. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16399. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16400. return this;
  16401. };
  16402. /**
  16403. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16404. * Supports definition of mesh facing forward or backward.
  16405. * @param {number} flipBack
  16406. * @param {number} twirlClockwise
  16407. * @param {number} tiltRight
  16408. *
  16409. * Returns a new Vector3.
  16410. */
  16411. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16412. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16413. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16414. };
  16415. /**
  16416. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16417. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16418. */
  16419. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16420. if (includeDescendants === void 0) { includeDescendants = true; }
  16421. this.computeWorldMatrix(true);
  16422. var min;
  16423. var max;
  16424. var boundingInfo = this.getBoundingInfo();
  16425. if (!this.subMeshes) {
  16426. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16427. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16428. }
  16429. else {
  16430. min = boundingInfo.boundingBox.minimumWorld;
  16431. max = boundingInfo.boundingBox.maximumWorld;
  16432. }
  16433. if (includeDescendants) {
  16434. var descendants = this.getDescendants(false);
  16435. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16436. var descendant = descendants_1[_i];
  16437. var childMesh = descendant;
  16438. childMesh.computeWorldMatrix(true);
  16439. //make sure we have the needed params to get mix and max
  16440. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16441. continue;
  16442. }
  16443. var childBoundingInfo = childMesh.getBoundingInfo();
  16444. var boundingBox = childBoundingInfo.boundingBox;
  16445. var minBox = boundingBox.minimumWorld;
  16446. var maxBox = boundingBox.maximumWorld;
  16447. BABYLON.Tools.CheckExtends(minBox, min, max);
  16448. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16449. }
  16450. }
  16451. return {
  16452. min: min,
  16453. max: max
  16454. };
  16455. };
  16456. /**
  16457. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16458. * Returns the AbstractMesh.
  16459. */
  16460. AbstractMesh.prototype._updateBoundingInfo = function () {
  16461. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16462. this._boundingInfo.update(this.worldMatrixFromCache);
  16463. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16464. return this;
  16465. };
  16466. /**
  16467. * Update a mesh's children BoundingInfo objects only.
  16468. * Returns the AbstractMesh.
  16469. */
  16470. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16471. if (!this.subMeshes) {
  16472. return this;
  16473. }
  16474. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16475. var subMesh = this.subMeshes[subIndex];
  16476. if (!subMesh.IsGlobal) {
  16477. subMesh.updateBoundingInfo(matrix);
  16478. }
  16479. }
  16480. return this;
  16481. };
  16482. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16483. // Bounding info
  16484. this._updateBoundingInfo();
  16485. };
  16486. /**
  16487. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16488. * A mesh is in the frustum if its bounding box intersects the frustum.
  16489. * Boolean returned.
  16490. */
  16491. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16492. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16493. };
  16494. /**
  16495. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16496. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16497. * Boolean returned.
  16498. */
  16499. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16500. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16501. ;
  16502. };
  16503. /**
  16504. * True if the mesh intersects another mesh or a SolidParticle object.
  16505. * 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)
  16506. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16507. * Returns a boolean.
  16508. */
  16509. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16510. if (precise === void 0) { precise = false; }
  16511. if (!this._boundingInfo || !mesh._boundingInfo) {
  16512. return false;
  16513. }
  16514. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16515. return true;
  16516. }
  16517. if (includeDescendants) {
  16518. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16519. var child = _a[_i];
  16520. if (child.intersectsMesh(mesh, precise, true)) {
  16521. return true;
  16522. }
  16523. }
  16524. }
  16525. return false;
  16526. };
  16527. /**
  16528. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16529. * Returns a boolean.
  16530. */
  16531. AbstractMesh.prototype.intersectsPoint = function (point) {
  16532. if (!this._boundingInfo) {
  16533. return false;
  16534. }
  16535. return this._boundingInfo.intersectsPoint(point);
  16536. };
  16537. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16538. return this.physicsImpostor;
  16539. };
  16540. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16541. if (camera === void 0) { camera = null; }
  16542. if (!camera) {
  16543. camera = this.getScene().activeCamera;
  16544. }
  16545. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16546. };
  16547. /**
  16548. * Returns the distance from the mesh to the active camera.
  16549. * Returns a float.
  16550. */
  16551. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16552. if (camera === void 0) { camera = null; }
  16553. if (!camera) {
  16554. camera = this.getScene().activeCamera;
  16555. }
  16556. return this.absolutePosition.subtract(camera.position).length();
  16557. };
  16558. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16559. if (!this.physicsImpostor) {
  16560. return this;
  16561. }
  16562. this.physicsImpostor.applyImpulse(force, contactPoint);
  16563. return this;
  16564. };
  16565. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16566. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16567. return this;
  16568. }
  16569. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16570. mainPivot: pivot1,
  16571. connectedPivot: pivot2,
  16572. nativeParams: options
  16573. });
  16574. return this;
  16575. };
  16576. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16577. // Collisions
  16578. /**
  16579. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16580. * Default `false`.
  16581. */
  16582. get: function () {
  16583. return this._checkCollisions;
  16584. },
  16585. set: function (collisionEnabled) {
  16586. this._checkCollisions = collisionEnabled;
  16587. if (this.getScene().workerCollisions) {
  16588. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16589. }
  16590. },
  16591. enumerable: true,
  16592. configurable: true
  16593. });
  16594. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16595. /**
  16596. * Gets Collider object used to compute collisions (not physics)
  16597. */
  16598. get: function () {
  16599. return this._collider;
  16600. },
  16601. enumerable: true,
  16602. configurable: true
  16603. });
  16604. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16605. var globalPosition = this.getAbsolutePosition();
  16606. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16607. if (!this._collider) {
  16608. this._collider = new BABYLON.Collider();
  16609. }
  16610. this._collider._radius = this.ellipsoid;
  16611. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16612. return this;
  16613. };
  16614. // Submeshes octree
  16615. /**
  16616. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16617. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16618. * Returns an Octree of submeshes.
  16619. */
  16620. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16621. if (maxCapacity === void 0) { maxCapacity = 64; }
  16622. if (maxDepth === void 0) { maxDepth = 2; }
  16623. if (!this._submeshesOctree) {
  16624. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16625. }
  16626. this.computeWorldMatrix(true);
  16627. var boundingInfo = this.getBoundingInfo();
  16628. // Update octree
  16629. var bbox = boundingInfo.boundingBox;
  16630. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16631. return this._submeshesOctree;
  16632. };
  16633. // Collisions
  16634. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16635. this._generatePointsArray();
  16636. if (!this._positions) {
  16637. return this;
  16638. }
  16639. // Transformation
  16640. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16641. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16642. subMesh._lastColliderWorldVertices = [];
  16643. subMesh._trianglePlanes = [];
  16644. var start = subMesh.verticesStart;
  16645. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16646. for (var i = start; i < end; i++) {
  16647. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16648. }
  16649. }
  16650. // Collide
  16651. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16652. if (collider.collisionFound) {
  16653. collider.collidedMesh = this;
  16654. }
  16655. return this;
  16656. };
  16657. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16658. var subMeshes;
  16659. var len;
  16660. // Octrees
  16661. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16662. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16663. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16664. len = intersections.length;
  16665. subMeshes = intersections.data;
  16666. }
  16667. else {
  16668. subMeshes = this.subMeshes;
  16669. len = subMeshes.length;
  16670. }
  16671. for (var index = 0; index < len; index++) {
  16672. var subMesh = subMeshes[index];
  16673. // Bounding test
  16674. if (len > 1 && !subMesh._checkCollision(collider))
  16675. continue;
  16676. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16677. }
  16678. return this;
  16679. };
  16680. AbstractMesh.prototype._checkCollision = function (collider) {
  16681. // Bounding box test
  16682. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16683. return this;
  16684. // Transformation matrix
  16685. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16686. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16687. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16688. return this;
  16689. };
  16690. // Picking
  16691. AbstractMesh.prototype._generatePointsArray = function () {
  16692. return false;
  16693. };
  16694. /**
  16695. * Checks if the passed Ray intersects with the mesh.
  16696. * Returns an object PickingInfo.
  16697. */
  16698. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16699. var pickingInfo = new BABYLON.PickingInfo();
  16700. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16701. return pickingInfo;
  16702. }
  16703. if (!this._generatePointsArray()) {
  16704. return pickingInfo;
  16705. }
  16706. var intersectInfo = null;
  16707. // Octrees
  16708. var subMeshes;
  16709. var len;
  16710. if (this._submeshesOctree && this.useOctreeForPicking) {
  16711. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16712. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16713. len = intersections.length;
  16714. subMeshes = intersections.data;
  16715. }
  16716. else {
  16717. subMeshes = this.subMeshes;
  16718. len = subMeshes.length;
  16719. }
  16720. for (var index = 0; index < len; index++) {
  16721. var subMesh = subMeshes[index];
  16722. // Bounding test
  16723. if (len > 1 && !subMesh.canIntersects(ray))
  16724. continue;
  16725. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16726. if (currentIntersectInfo) {
  16727. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16728. intersectInfo = currentIntersectInfo;
  16729. intersectInfo.subMeshId = index;
  16730. if (fastCheck) {
  16731. break;
  16732. }
  16733. }
  16734. }
  16735. }
  16736. if (intersectInfo) {
  16737. // Get picked point
  16738. var world = this.getWorldMatrix();
  16739. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16740. var direction = ray.direction.clone();
  16741. direction = direction.scale(intersectInfo.distance);
  16742. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16743. var pickedPoint = worldOrigin.add(worldDirection);
  16744. // Return result
  16745. pickingInfo.hit = true;
  16746. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16747. pickingInfo.pickedPoint = pickedPoint;
  16748. pickingInfo.pickedMesh = this;
  16749. pickingInfo.bu = intersectInfo.bu || 0;
  16750. pickingInfo.bv = intersectInfo.bv || 0;
  16751. pickingInfo.faceId = intersectInfo.faceId;
  16752. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16753. return pickingInfo;
  16754. }
  16755. return pickingInfo;
  16756. };
  16757. /**
  16758. * Clones the mesh, used by the class Mesh.
  16759. * Just returns `null` for an AbstractMesh.
  16760. */
  16761. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16762. return null;
  16763. };
  16764. /**
  16765. * Disposes all the mesh submeshes.
  16766. * Returns the AbstractMesh.
  16767. */
  16768. AbstractMesh.prototype.releaseSubMeshes = function () {
  16769. if (this.subMeshes) {
  16770. while (this.subMeshes.length) {
  16771. this.subMeshes[0].dispose();
  16772. }
  16773. }
  16774. else {
  16775. this.subMeshes = new Array();
  16776. }
  16777. return this;
  16778. };
  16779. /**
  16780. * Disposes the AbstractMesh.
  16781. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16782. * Returns nothing.
  16783. */
  16784. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16785. var _this = this;
  16786. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16787. var index;
  16788. // Action manager
  16789. if (this.actionManager !== undefined && this.actionManager !== null) {
  16790. this.actionManager.dispose();
  16791. this.actionManager = null;
  16792. }
  16793. // Skeleton
  16794. this.skeleton = null;
  16795. // Physics
  16796. if (this.physicsImpostor) {
  16797. this.physicsImpostor.dispose();
  16798. }
  16799. // Intersections in progress
  16800. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16801. var other = this._intersectionsInProgress[index];
  16802. var pos = other._intersectionsInProgress.indexOf(this);
  16803. other._intersectionsInProgress.splice(pos, 1);
  16804. }
  16805. this._intersectionsInProgress = [];
  16806. // Lights
  16807. var lights = this.getScene().lights;
  16808. lights.forEach(function (light) {
  16809. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16810. if (meshIndex !== -1) {
  16811. light.includedOnlyMeshes.splice(meshIndex, 1);
  16812. }
  16813. meshIndex = light.excludedMeshes.indexOf(_this);
  16814. if (meshIndex !== -1) {
  16815. light.excludedMeshes.splice(meshIndex, 1);
  16816. }
  16817. // Shadow generators
  16818. var generator = light.getShadowGenerator();
  16819. if (generator) {
  16820. var shadowMap = generator.getShadowMap();
  16821. if (shadowMap && shadowMap.renderList) {
  16822. meshIndex = shadowMap.renderList.indexOf(_this);
  16823. if (meshIndex !== -1) {
  16824. shadowMap.renderList.splice(meshIndex, 1);
  16825. }
  16826. }
  16827. }
  16828. });
  16829. // Edges
  16830. if (this._edgesRenderer) {
  16831. this._edgesRenderer.dispose();
  16832. this._edgesRenderer = null;
  16833. }
  16834. // SubMeshes
  16835. if (this.getClassName() !== "InstancedMesh") {
  16836. this.releaseSubMeshes();
  16837. }
  16838. // Octree
  16839. var sceneOctree = this.getScene().selectionOctree;
  16840. if (sceneOctree !== undefined && sceneOctree !== null) {
  16841. var index = sceneOctree.dynamicContent.indexOf(this);
  16842. if (index !== -1) {
  16843. sceneOctree.dynamicContent.splice(index, 1);
  16844. }
  16845. }
  16846. // Query
  16847. var engine = this.getScene().getEngine();
  16848. if (this._occlusionQuery) {
  16849. this._isOcclusionQueryInProgress = false;
  16850. engine.deleteQuery(this._occlusionQuery);
  16851. this._occlusionQuery = null;
  16852. }
  16853. // Engine
  16854. engine.wipeCaches();
  16855. // Remove from scene
  16856. this.getScene().removeMesh(this);
  16857. if (disposeMaterialAndTextures) {
  16858. if (this.material) {
  16859. this.material.dispose(false, true);
  16860. }
  16861. }
  16862. if (!doNotRecurse) {
  16863. // Particles
  16864. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16865. if (this.getScene().particleSystems[index].emitter === this) {
  16866. this.getScene().particleSystems[index].dispose();
  16867. index--;
  16868. }
  16869. }
  16870. }
  16871. // facet data
  16872. if (this._facetDataEnabled) {
  16873. this.disableFacetData();
  16874. }
  16875. this.onAfterWorldMatrixUpdateObservable.clear();
  16876. this.onCollideObservable.clear();
  16877. this.onCollisionPositionChangeObservable.clear();
  16878. this._isDisposed = true;
  16879. _super.prototype.dispose.call(this, doNotRecurse);
  16880. };
  16881. /**
  16882. * Adds the passed mesh as a child to the current mesh.
  16883. * Returns the AbstractMesh.
  16884. */
  16885. AbstractMesh.prototype.addChild = function (mesh) {
  16886. mesh.setParent(this);
  16887. return this;
  16888. };
  16889. /**
  16890. * Removes the passed mesh from the current mesh children list.
  16891. * Returns the AbstractMesh.
  16892. */
  16893. AbstractMesh.prototype.removeChild = function (mesh) {
  16894. mesh.setParent(null);
  16895. return this;
  16896. };
  16897. // Facet data
  16898. /**
  16899. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16900. * Returns the AbstractMesh.
  16901. */
  16902. AbstractMesh.prototype._initFacetData = function () {
  16903. if (!this._facetNormals) {
  16904. this._facetNormals = new Array();
  16905. }
  16906. if (!this._facetPositions) {
  16907. this._facetPositions = new Array();
  16908. }
  16909. if (!this._facetPartitioning) {
  16910. this._facetPartitioning = new Array();
  16911. }
  16912. this._facetNb = (this.getIndices().length / 3) | 0;
  16913. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16914. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16915. for (var f = 0; f < this._facetNb; f++) {
  16916. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16917. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16918. }
  16919. this._facetDataEnabled = true;
  16920. return this;
  16921. };
  16922. /**
  16923. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16924. * This method can be called within the render loop.
  16925. * 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.
  16926. * Returns the AbstractMesh.
  16927. */
  16928. AbstractMesh.prototype.updateFacetData = function () {
  16929. if (!this._facetDataEnabled) {
  16930. this._initFacetData();
  16931. }
  16932. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16933. var indices = this.getIndices();
  16934. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16935. var bInfo = this.getBoundingInfo();
  16936. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16937. // init arrays, matrix and sort function on first call
  16938. this._facetDepthSortEnabled = true;
  16939. if (indices instanceof Uint16Array) {
  16940. this._depthSortedIndices = new Uint16Array(indices);
  16941. }
  16942. else if (indices instanceof Uint32Array) {
  16943. this._depthSortedIndices = new Uint32Array(indices);
  16944. }
  16945. else {
  16946. var needs32bits = false;
  16947. for (var i = 0; i < indices.length; i++) {
  16948. if (indices[i] > 65535) {
  16949. needs32bits = true;
  16950. break;
  16951. }
  16952. }
  16953. if (needs32bits) {
  16954. this._depthSortedIndices = new Uint32Array(indices);
  16955. }
  16956. else {
  16957. this._depthSortedIndices = new Uint16Array(indices);
  16958. }
  16959. }
  16960. this._facetDepthSortFunction = function (f1, f2) {
  16961. return (f2.sqDistance - f1.sqDistance);
  16962. };
  16963. if (!this._facetDepthSortFrom) {
  16964. var camera = this.getScene().activeCamera;
  16965. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16966. }
  16967. this._depthSortedFacets = [];
  16968. for (var f = 0; f < this._facetNb; f++) {
  16969. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16970. this._depthSortedFacets.push(depthSortedFacet);
  16971. }
  16972. this._invertedMatrix = BABYLON.Matrix.Identity();
  16973. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16974. }
  16975. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16976. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16977. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16978. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16979. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16980. this._subDiv.max = this._partitioningSubdivisions;
  16981. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16982. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16983. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16984. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16985. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16986. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16987. // set the parameters for ComputeNormals()
  16988. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16989. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16990. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16991. this._facetParameters.bInfo = bInfo;
  16992. this._facetParameters.bbSize = this._bbSize;
  16993. this._facetParameters.subDiv = this._subDiv;
  16994. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16995. this._facetParameters.depthSort = this._facetDepthSort;
  16996. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16997. this.computeWorldMatrix(true);
  16998. this._worldMatrix.invertToRef(this._invertedMatrix);
  16999. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17000. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17001. }
  17002. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17003. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17004. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17005. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17006. var l = (this._depthSortedIndices.length / 3) | 0;
  17007. for (var f = 0; f < l; f++) {
  17008. var sind = this._depthSortedFacets[f].ind;
  17009. this._depthSortedIndices[f * 3] = indices[sind];
  17010. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17011. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17012. }
  17013. this.updateIndices(this._depthSortedIndices);
  17014. }
  17015. return this;
  17016. };
  17017. /**
  17018. * Returns the facetLocalNormals array.
  17019. * The normals are expressed in the mesh local space.
  17020. */
  17021. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17022. if (!this._facetNormals) {
  17023. this.updateFacetData();
  17024. }
  17025. return this._facetNormals;
  17026. };
  17027. /**
  17028. * Returns the facetLocalPositions array.
  17029. * The facet positions are expressed in the mesh local space.
  17030. */
  17031. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17032. if (!this._facetPositions) {
  17033. this.updateFacetData();
  17034. }
  17035. return this._facetPositions;
  17036. };
  17037. /**
  17038. * Returns the facetLocalPartioning array.
  17039. */
  17040. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17041. if (!this._facetPartitioning) {
  17042. this.updateFacetData();
  17043. }
  17044. return this._facetPartitioning;
  17045. };
  17046. /**
  17047. * Returns the i-th facet position in the world system.
  17048. * This method allocates a new Vector3 per call.
  17049. */
  17050. AbstractMesh.prototype.getFacetPosition = function (i) {
  17051. var pos = BABYLON.Vector3.Zero();
  17052. this.getFacetPositionToRef(i, pos);
  17053. return pos;
  17054. };
  17055. /**
  17056. * Sets the reference Vector3 with the i-th facet position in the world system.
  17057. * Returns the AbstractMesh.
  17058. */
  17059. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17060. var localPos = (this.getFacetLocalPositions())[i];
  17061. var world = this.getWorldMatrix();
  17062. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17063. return this;
  17064. };
  17065. /**
  17066. * Returns the i-th facet normal in the world system.
  17067. * This method allocates a new Vector3 per call.
  17068. */
  17069. AbstractMesh.prototype.getFacetNormal = function (i) {
  17070. var norm = BABYLON.Vector3.Zero();
  17071. this.getFacetNormalToRef(i, norm);
  17072. return norm;
  17073. };
  17074. /**
  17075. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17076. * Returns the AbstractMesh.
  17077. */
  17078. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17079. var localNorm = (this.getFacetLocalNormals())[i];
  17080. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17081. return this;
  17082. };
  17083. /**
  17084. * 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).
  17085. */
  17086. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17087. var bInfo = this.getBoundingInfo();
  17088. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17089. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17090. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17091. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17092. return null;
  17093. }
  17094. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17095. };
  17096. /**
  17097. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17098. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17099. * If checkFace is 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.
  17100. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17101. * 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.
  17102. */
  17103. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17104. if (checkFace === void 0) { checkFace = false; }
  17105. if (facing === void 0) { facing = true; }
  17106. var world = this.getWorldMatrix();
  17107. var invMat = BABYLON.Tmp.Matrix[5];
  17108. world.invertToRef(invMat);
  17109. var invVect = BABYLON.Tmp.Vector3[8];
  17110. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17111. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17112. if (projected) {
  17113. // tranform the local computed projected vector to world coordinates
  17114. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17115. }
  17116. return closest;
  17117. };
  17118. /**
  17119. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17120. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17121. * If checkFace is 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.
  17122. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17123. * 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.
  17124. */
  17125. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17126. if (checkFace === void 0) { checkFace = false; }
  17127. if (facing === void 0) { facing = true; }
  17128. var closest = null;
  17129. var tmpx = 0.0;
  17130. var tmpy = 0.0;
  17131. var tmpz = 0.0;
  17132. var d = 0.0; // tmp dot facet normal * facet position
  17133. var t0 = 0.0;
  17134. var projx = 0.0;
  17135. var projy = 0.0;
  17136. var projz = 0.0;
  17137. // Get all the facets in the same partitioning block than (x, y, z)
  17138. var facetPositions = this.getFacetLocalPositions();
  17139. var facetNormals = this.getFacetLocalNormals();
  17140. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17141. if (!facetsInBlock) {
  17142. return null;
  17143. }
  17144. // Get the closest facet to (x, y, z)
  17145. var shortest = Number.MAX_VALUE; // init distance vars
  17146. var tmpDistance = shortest;
  17147. var fib; // current facet in the block
  17148. var norm; // current facet normal
  17149. var p0; // current facet barycenter position
  17150. // loop on all the facets in the current partitioning block
  17151. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17152. fib = facetsInBlock[idx];
  17153. norm = facetNormals[fib];
  17154. p0 = facetPositions[fib];
  17155. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17156. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17157. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17158. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17159. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17160. projx = x + norm.x * t0;
  17161. projy = y + norm.y * t0;
  17162. projz = z + norm.z * t0;
  17163. tmpx = projx - x;
  17164. tmpy = projy - y;
  17165. tmpz = projz - z;
  17166. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17167. if (tmpDistance < shortest) {
  17168. shortest = tmpDistance;
  17169. closest = fib;
  17170. if (projected) {
  17171. projected.x = projx;
  17172. projected.y = projy;
  17173. projected.z = projz;
  17174. }
  17175. }
  17176. }
  17177. }
  17178. return closest;
  17179. };
  17180. /**
  17181. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17182. */
  17183. AbstractMesh.prototype.getFacetDataParameters = function () {
  17184. return this._facetParameters;
  17185. };
  17186. /**
  17187. * Disables the feature FacetData and frees the related memory.
  17188. * Returns the AbstractMesh.
  17189. */
  17190. AbstractMesh.prototype.disableFacetData = function () {
  17191. if (this._facetDataEnabled) {
  17192. this._facetDataEnabled = false;
  17193. this._facetPositions = new Array();
  17194. this._facetNormals = new Array();
  17195. this._facetPartitioning = new Array();
  17196. this._facetParameters = null;
  17197. this._depthSortedIndices = new Uint32Array(0);
  17198. }
  17199. return this;
  17200. };
  17201. /**
  17202. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17203. * Returns the mesh.
  17204. */
  17205. AbstractMesh.prototype.updateIndices = function (indices) {
  17206. return this;
  17207. };
  17208. /**
  17209. * The mesh Geometry. Actually used by the Mesh object.
  17210. * Returns a blank geometry object.
  17211. */
  17212. /**
  17213. * Creates new normals data for the mesh.
  17214. * @param updatable.
  17215. */
  17216. AbstractMesh.prototype.createNormals = function (updatable) {
  17217. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17218. var indices = this.getIndices();
  17219. var normals;
  17220. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17221. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17222. }
  17223. else {
  17224. normals = [];
  17225. }
  17226. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17227. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17228. };
  17229. /**
  17230. * Align the mesh with a normal.
  17231. * Returns the mesh.
  17232. */
  17233. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17234. if (!upDirection) {
  17235. upDirection = BABYLON.Axis.Y;
  17236. }
  17237. var axisX = BABYLON.Tmp.Vector3[0];
  17238. var axisZ = BABYLON.Tmp.Vector3[1];
  17239. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17240. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17241. if (this.rotationQuaternion) {
  17242. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17243. }
  17244. else {
  17245. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17246. }
  17247. return this;
  17248. };
  17249. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17250. var engine = this.getEngine();
  17251. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17252. this._isOccluded = false;
  17253. return;
  17254. }
  17255. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17256. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17257. if (isOcclusionQueryAvailable) {
  17258. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17259. this._isOcclusionQueryInProgress = false;
  17260. this._occlusionInternalRetryCounter = 0;
  17261. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17262. }
  17263. else {
  17264. this._occlusionInternalRetryCounter++;
  17265. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17266. this._isOcclusionQueryInProgress = false;
  17267. this._occlusionInternalRetryCounter = 0;
  17268. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17269. // if strict continue the last state of the object.
  17270. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17271. }
  17272. else {
  17273. return;
  17274. }
  17275. }
  17276. }
  17277. var scene = this.getScene();
  17278. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17279. if (!this._occlusionQuery) {
  17280. this._occlusionQuery = engine.createQuery();
  17281. }
  17282. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17283. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17284. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17285. this._isOcclusionQueryInProgress = true;
  17286. };
  17287. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17288. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17289. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17290. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17291. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17292. return AbstractMesh;
  17293. }(BABYLON.TransformNode));
  17294. BABYLON.AbstractMesh = AbstractMesh;
  17295. })(BABYLON || (BABYLON = {}));
  17296. //# sourceMappingURL=babylon.abstractMesh.js.map
  17297. var BABYLON;
  17298. (function (BABYLON) {
  17299. var Light = /** @class */ (function (_super) {
  17300. __extends(Light, _super);
  17301. /**
  17302. * Creates a Light object in the scene.
  17303. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17304. */
  17305. function Light(name, scene) {
  17306. var _this = _super.call(this, name, scene) || this;
  17307. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17308. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17309. _this.intensity = 1.0;
  17310. _this.range = Number.MAX_VALUE;
  17311. /**
  17312. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17313. * of light.
  17314. */
  17315. _this._photometricScale = 1.0;
  17316. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17317. _this._radius = 0.00001;
  17318. _this.renderPriority = 0;
  17319. /**
  17320. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17321. * the current shadow generator.
  17322. */
  17323. _this.shadowEnabled = true;
  17324. _this._excludeWithLayerMask = 0;
  17325. _this._includeOnlyWithLayerMask = 0;
  17326. _this._lightmapMode = 0;
  17327. _this._excludedMeshesIds = new Array();
  17328. _this._includedOnlyMeshesIds = new Array();
  17329. _this.getScene().addLight(_this);
  17330. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17331. _this._buildUniformLayout();
  17332. _this.includedOnlyMeshes = new Array();
  17333. _this.excludedMeshes = new Array();
  17334. _this._resyncMeshes();
  17335. return _this;
  17336. }
  17337. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17338. /**
  17339. * If every light affecting the material is in this lightmapMode,
  17340. * material.lightmapTexture adds or multiplies
  17341. * (depends on material.useLightmapAsShadowmap)
  17342. * after every other light calculations.
  17343. */
  17344. get: function () {
  17345. return Light._LIGHTMAP_DEFAULT;
  17346. },
  17347. enumerable: true,
  17348. configurable: true
  17349. });
  17350. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17351. /**
  17352. * material.lightmapTexture as only diffuse lighting from this light
  17353. * adds only specular lighting from this light
  17354. * adds dynamic shadows
  17355. */
  17356. get: function () {
  17357. return Light._LIGHTMAP_SPECULAR;
  17358. },
  17359. enumerable: true,
  17360. configurable: true
  17361. });
  17362. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17363. /**
  17364. * material.lightmapTexture as only lighting
  17365. * no light calculation from this light
  17366. * only adds dynamic shadows from this light
  17367. */
  17368. get: function () {
  17369. return Light._LIGHTMAP_SHADOWSONLY;
  17370. },
  17371. enumerable: true,
  17372. configurable: true
  17373. });
  17374. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17375. /**
  17376. * Each light type uses the default quantity according to its type:
  17377. * point/spot lights use luminous intensity
  17378. * directional lights use illuminance
  17379. */
  17380. get: function () {
  17381. return Light._INTENSITYMODE_AUTOMATIC;
  17382. },
  17383. enumerable: true,
  17384. configurable: true
  17385. });
  17386. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17387. /**
  17388. * lumen (lm)
  17389. */
  17390. get: function () {
  17391. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17392. },
  17393. enumerable: true,
  17394. configurable: true
  17395. });
  17396. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17397. /**
  17398. * candela (lm/sr)
  17399. */
  17400. get: function () {
  17401. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17402. },
  17403. enumerable: true,
  17404. configurable: true
  17405. });
  17406. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17407. /**
  17408. * lux (lm/m^2)
  17409. */
  17410. get: function () {
  17411. return Light._INTENSITYMODE_ILLUMINANCE;
  17412. },
  17413. enumerable: true,
  17414. configurable: true
  17415. });
  17416. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17417. /**
  17418. * nit (cd/m^2)
  17419. */
  17420. get: function () {
  17421. return Light._INTENSITYMODE_LUMINANCE;
  17422. },
  17423. enumerable: true,
  17424. configurable: true
  17425. });
  17426. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17427. /**
  17428. * Light type const id of the point light.
  17429. */
  17430. get: function () {
  17431. return Light._LIGHTTYPEID_POINTLIGHT;
  17432. },
  17433. enumerable: true,
  17434. configurable: true
  17435. });
  17436. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17437. /**
  17438. * Light type const id of the directional light.
  17439. */
  17440. get: function () {
  17441. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17442. },
  17443. enumerable: true,
  17444. configurable: true
  17445. });
  17446. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17447. /**
  17448. * Light type const id of the spot light.
  17449. */
  17450. get: function () {
  17451. return Light._LIGHTTYPEID_SPOTLIGHT;
  17452. },
  17453. enumerable: true,
  17454. configurable: true
  17455. });
  17456. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17457. /**
  17458. * Light type const id of the hemispheric light.
  17459. */
  17460. get: function () {
  17461. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17462. },
  17463. enumerable: true,
  17464. configurable: true
  17465. });
  17466. Object.defineProperty(Light.prototype, "intensityMode", {
  17467. /**
  17468. * Gets the photometric scale used to interpret the intensity.
  17469. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17470. */
  17471. get: function () {
  17472. return this._intensityMode;
  17473. },
  17474. /**
  17475. * Sets the photometric scale used to interpret the intensity.
  17476. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17477. */
  17478. set: function (value) {
  17479. this._intensityMode = value;
  17480. this._computePhotometricScale();
  17481. },
  17482. enumerable: true,
  17483. configurable: true
  17484. });
  17485. ;
  17486. ;
  17487. Object.defineProperty(Light.prototype, "radius", {
  17488. /**
  17489. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17490. */
  17491. get: function () {
  17492. return this._radius;
  17493. },
  17494. /**
  17495. * sets the light radius used by PBR Materials to simulate soft area lights.
  17496. */
  17497. set: function (value) {
  17498. this._radius = value;
  17499. this._computePhotometricScale();
  17500. },
  17501. enumerable: true,
  17502. configurable: true
  17503. });
  17504. ;
  17505. ;
  17506. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17507. get: function () {
  17508. return this._includedOnlyMeshes;
  17509. },
  17510. set: function (value) {
  17511. this._includedOnlyMeshes = value;
  17512. this._hookArrayForIncludedOnly(value);
  17513. },
  17514. enumerable: true,
  17515. configurable: true
  17516. });
  17517. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17518. get: function () {
  17519. return this._excludedMeshes;
  17520. },
  17521. set: function (value) {
  17522. this._excludedMeshes = value;
  17523. this._hookArrayForExcluded(value);
  17524. },
  17525. enumerable: true,
  17526. configurable: true
  17527. });
  17528. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17529. get: function () {
  17530. return this._excludeWithLayerMask;
  17531. },
  17532. set: function (value) {
  17533. this._excludeWithLayerMask = value;
  17534. this._resyncMeshes();
  17535. },
  17536. enumerable: true,
  17537. configurable: true
  17538. });
  17539. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17540. get: function () {
  17541. return this._includeOnlyWithLayerMask;
  17542. },
  17543. set: function (value) {
  17544. this._includeOnlyWithLayerMask = value;
  17545. this._resyncMeshes();
  17546. },
  17547. enumerable: true,
  17548. configurable: true
  17549. });
  17550. Object.defineProperty(Light.prototype, "lightmapMode", {
  17551. get: function () {
  17552. return this._lightmapMode;
  17553. },
  17554. set: function (value) {
  17555. if (this._lightmapMode === value) {
  17556. return;
  17557. }
  17558. this._lightmapMode = value;
  17559. this._markMeshesAsLightDirty();
  17560. },
  17561. enumerable: true,
  17562. configurable: true
  17563. });
  17564. Light.prototype._buildUniformLayout = function () {
  17565. // Overridden
  17566. };
  17567. /**
  17568. * Returns the string "Light".
  17569. */
  17570. Light.prototype.getClassName = function () {
  17571. return "Light";
  17572. };
  17573. /**
  17574. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17575. */
  17576. Light.prototype.toString = function (fullDetails) {
  17577. var ret = "Name: " + this.name;
  17578. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17579. if (this.animations) {
  17580. for (var i = 0; i < this.animations.length; i++) {
  17581. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17582. }
  17583. }
  17584. if (fullDetails) {
  17585. }
  17586. return ret;
  17587. };
  17588. /**
  17589. * Set the enabled state of this node.
  17590. * @param {boolean} value - the new enabled state
  17591. * @see isEnabled
  17592. */
  17593. Light.prototype.setEnabled = function (value) {
  17594. _super.prototype.setEnabled.call(this, value);
  17595. this._resyncMeshes();
  17596. };
  17597. /**
  17598. * Returns the Light associated shadow generator.
  17599. */
  17600. Light.prototype.getShadowGenerator = function () {
  17601. return this._shadowGenerator;
  17602. };
  17603. /**
  17604. * Returns a Vector3, the absolute light position in the World.
  17605. */
  17606. Light.prototype.getAbsolutePosition = function () {
  17607. return BABYLON.Vector3.Zero();
  17608. };
  17609. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17610. };
  17611. Light.prototype._getWorldMatrix = function () {
  17612. return BABYLON.Matrix.Identity();
  17613. };
  17614. /**
  17615. * Boolean : True if the light will affect the passed mesh.
  17616. */
  17617. Light.prototype.canAffectMesh = function (mesh) {
  17618. if (!mesh) {
  17619. return true;
  17620. }
  17621. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17622. return false;
  17623. }
  17624. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17625. return false;
  17626. }
  17627. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17628. return false;
  17629. }
  17630. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17631. return false;
  17632. }
  17633. return true;
  17634. };
  17635. /**
  17636. * Returns the light World matrix.
  17637. */
  17638. Light.prototype.getWorldMatrix = function () {
  17639. this._currentRenderId = this.getScene().getRenderId();
  17640. var worldMatrix = this._getWorldMatrix();
  17641. if (this.parent && this.parent.getWorldMatrix) {
  17642. if (!this._parentedWorldMatrix) {
  17643. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17644. }
  17645. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17646. this._markSyncedWithParent();
  17647. return this._parentedWorldMatrix;
  17648. }
  17649. return worldMatrix;
  17650. };
  17651. /**
  17652. * Sort function to order lights for rendering.
  17653. * @param a First Light object to compare to second.
  17654. * @param b Second Light object to compare first.
  17655. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17656. */
  17657. Light.compareLightsPriority = function (a, b) {
  17658. //shadow-casting lights have priority over non-shadow-casting lights
  17659. //the renderPrioirty is a secondary sort criterion
  17660. if (a.shadowEnabled !== b.shadowEnabled) {
  17661. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17662. }
  17663. return b.renderPriority - a.renderPriority;
  17664. };
  17665. /**
  17666. * Disposes the light.
  17667. */
  17668. Light.prototype.dispose = function () {
  17669. if (this._shadowGenerator) {
  17670. this._shadowGenerator.dispose();
  17671. this._shadowGenerator = null;
  17672. }
  17673. // Animations
  17674. this.getScene().stopAnimation(this);
  17675. this._uniformBuffer.dispose();
  17676. // Remove from scene
  17677. this.getScene().removeLight(this);
  17678. _super.prototype.dispose.call(this);
  17679. };
  17680. /**
  17681. * Returns the light type ID (integer).
  17682. */
  17683. Light.prototype.getTypeID = function () {
  17684. return 0;
  17685. };
  17686. /**
  17687. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17688. */
  17689. Light.prototype.getScaledIntensity = function () {
  17690. return this._photometricScale * this.intensity;
  17691. };
  17692. /**
  17693. * Returns a new Light object, named "name", from the current one.
  17694. */
  17695. Light.prototype.clone = function (name) {
  17696. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17697. if (!constructor) {
  17698. return null;
  17699. }
  17700. return BABYLON.SerializationHelper.Clone(constructor, this);
  17701. };
  17702. /**
  17703. * Serializes the current light into a Serialization object.
  17704. * Returns the serialized object.
  17705. */
  17706. Light.prototype.serialize = function () {
  17707. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17708. // Type
  17709. serializationObject.type = this.getTypeID();
  17710. // Parent
  17711. if (this.parent) {
  17712. serializationObject.parentId = this.parent.id;
  17713. }
  17714. // Inclusion / exclusions
  17715. if (this.excludedMeshes.length > 0) {
  17716. serializationObject.excludedMeshesIds = [];
  17717. this.excludedMeshes.forEach(function (mesh) {
  17718. serializationObject.excludedMeshesIds.push(mesh.id);
  17719. });
  17720. }
  17721. if (this.includedOnlyMeshes.length > 0) {
  17722. serializationObject.includedOnlyMeshesIds = [];
  17723. this.includedOnlyMeshes.forEach(function (mesh) {
  17724. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17725. });
  17726. }
  17727. // Animations
  17728. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17729. serializationObject.ranges = this.serializeAnimationRanges();
  17730. return serializationObject;
  17731. };
  17732. /**
  17733. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17734. * This new light is named "name" and added to the passed scene.
  17735. */
  17736. Light.GetConstructorFromName = function (type, name, scene) {
  17737. switch (type) {
  17738. case 0:
  17739. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17740. case 1:
  17741. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17742. case 2:
  17743. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17744. case 3:
  17745. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17746. }
  17747. return null;
  17748. };
  17749. /**
  17750. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17751. */
  17752. Light.Parse = function (parsedLight, scene) {
  17753. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17754. if (!constructor) {
  17755. return null;
  17756. }
  17757. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17758. // Inclusion / exclusions
  17759. if (parsedLight.excludedMeshesIds) {
  17760. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17761. }
  17762. if (parsedLight.includedOnlyMeshesIds) {
  17763. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17764. }
  17765. // Parent
  17766. if (parsedLight.parentId) {
  17767. light._waitingParentId = parsedLight.parentId;
  17768. }
  17769. // Animations
  17770. if (parsedLight.animations) {
  17771. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17772. var parsedAnimation = parsedLight.animations[animationIndex];
  17773. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17774. }
  17775. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17776. }
  17777. if (parsedLight.autoAnimate) {
  17778. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17779. }
  17780. return light;
  17781. };
  17782. Light.prototype._hookArrayForExcluded = function (array) {
  17783. var _this = this;
  17784. var oldPush = array.push;
  17785. array.push = function () {
  17786. var items = [];
  17787. for (var _i = 0; _i < arguments.length; _i++) {
  17788. items[_i] = arguments[_i];
  17789. }
  17790. var result = oldPush.apply(array, items);
  17791. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17792. var item = items_1[_a];
  17793. item._resyncLighSource(_this);
  17794. }
  17795. return result;
  17796. };
  17797. var oldSplice = array.splice;
  17798. array.splice = function (index, deleteCount) {
  17799. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17800. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17801. var item = deleted_1[_i];
  17802. item._resyncLighSource(_this);
  17803. }
  17804. return deleted;
  17805. };
  17806. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17807. var item = array_1[_i];
  17808. item._resyncLighSource(this);
  17809. }
  17810. };
  17811. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17812. var _this = this;
  17813. var oldPush = array.push;
  17814. array.push = function () {
  17815. var items = [];
  17816. for (var _i = 0; _i < arguments.length; _i++) {
  17817. items[_i] = arguments[_i];
  17818. }
  17819. var result = oldPush.apply(array, items);
  17820. _this._resyncMeshes();
  17821. return result;
  17822. };
  17823. var oldSplice = array.splice;
  17824. array.splice = function (index, deleteCount) {
  17825. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17826. _this._resyncMeshes();
  17827. return deleted;
  17828. };
  17829. this._resyncMeshes();
  17830. };
  17831. Light.prototype._resyncMeshes = function () {
  17832. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17833. var mesh = _a[_i];
  17834. mesh._resyncLighSource(this);
  17835. }
  17836. };
  17837. Light.prototype._markMeshesAsLightDirty = function () {
  17838. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17839. var mesh = _a[_i];
  17840. if (mesh._lightSources.indexOf(this) !== -1) {
  17841. mesh._markSubMeshesAsLightDirty();
  17842. }
  17843. }
  17844. };
  17845. /**
  17846. * Recomputes the cached photometric scale if needed.
  17847. */
  17848. Light.prototype._computePhotometricScale = function () {
  17849. this._photometricScale = this._getPhotometricScale();
  17850. this.getScene().resetCachedMaterial();
  17851. };
  17852. /**
  17853. * Returns the Photometric Scale according to the light type and intensity mode.
  17854. */
  17855. Light.prototype._getPhotometricScale = function () {
  17856. var photometricScale = 0.0;
  17857. var lightTypeID = this.getTypeID();
  17858. //get photometric mode
  17859. var photometricMode = this.intensityMode;
  17860. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17861. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17862. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17863. }
  17864. else {
  17865. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17866. }
  17867. }
  17868. //compute photometric scale
  17869. switch (lightTypeID) {
  17870. case Light.LIGHTTYPEID_POINTLIGHT:
  17871. case Light.LIGHTTYPEID_SPOTLIGHT:
  17872. switch (photometricMode) {
  17873. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17874. photometricScale = 1.0 / (4.0 * Math.PI);
  17875. break;
  17876. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17877. photometricScale = 1.0;
  17878. break;
  17879. case Light.INTENSITYMODE_LUMINANCE:
  17880. photometricScale = this.radius * this.radius;
  17881. break;
  17882. }
  17883. break;
  17884. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17885. switch (photometricMode) {
  17886. case Light.INTENSITYMODE_ILLUMINANCE:
  17887. photometricScale = 1.0;
  17888. break;
  17889. case Light.INTENSITYMODE_LUMINANCE:
  17890. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17891. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17892. var apexAngleRadians = this.radius;
  17893. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17894. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17895. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17896. photometricScale = solidAngle;
  17897. break;
  17898. }
  17899. break;
  17900. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17901. // No fall off in hemisperic light.
  17902. photometricScale = 1.0;
  17903. break;
  17904. }
  17905. return photometricScale;
  17906. };
  17907. Light.prototype._reorderLightsInScene = function () {
  17908. var scene = this.getScene();
  17909. if (this._renderPriority != 0) {
  17910. scene.requireLightSorting = true;
  17911. }
  17912. this.getScene().sortLightsByPriority();
  17913. };
  17914. //lightmapMode Consts
  17915. Light._LIGHTMAP_DEFAULT = 0;
  17916. Light._LIGHTMAP_SPECULAR = 1;
  17917. Light._LIGHTMAP_SHADOWSONLY = 2;
  17918. // Intensity Mode Consts
  17919. Light._INTENSITYMODE_AUTOMATIC = 0;
  17920. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17921. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17922. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17923. Light._INTENSITYMODE_LUMINANCE = 4;
  17924. // Light types ids const.
  17925. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17926. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17927. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17928. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17929. __decorate([
  17930. BABYLON.serializeAsColor3()
  17931. ], Light.prototype, "diffuse", void 0);
  17932. __decorate([
  17933. BABYLON.serializeAsColor3()
  17934. ], Light.prototype, "specular", void 0);
  17935. __decorate([
  17936. BABYLON.serialize()
  17937. ], Light.prototype, "intensity", void 0);
  17938. __decorate([
  17939. BABYLON.serialize()
  17940. ], Light.prototype, "range", void 0);
  17941. __decorate([
  17942. BABYLON.serialize()
  17943. ], Light.prototype, "intensityMode", null);
  17944. __decorate([
  17945. BABYLON.serialize()
  17946. ], Light.prototype, "radius", null);
  17947. __decorate([
  17948. BABYLON.serialize()
  17949. ], Light.prototype, "_renderPriority", void 0);
  17950. __decorate([
  17951. BABYLON.expandToProperty("_reorderLightsInScene")
  17952. ], Light.prototype, "renderPriority", void 0);
  17953. __decorate([
  17954. BABYLON.serialize()
  17955. ], Light.prototype, "shadowEnabled", void 0);
  17956. __decorate([
  17957. BABYLON.serialize("excludeWithLayerMask")
  17958. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17959. __decorate([
  17960. BABYLON.serialize("includeOnlyWithLayerMask")
  17961. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17962. __decorate([
  17963. BABYLON.serialize("lightmapMode")
  17964. ], Light.prototype, "_lightmapMode", void 0);
  17965. return Light;
  17966. }(BABYLON.Node));
  17967. BABYLON.Light = Light;
  17968. })(BABYLON || (BABYLON = {}));
  17969. //# sourceMappingURL=babylon.light.js.map
  17970. var BABYLON;
  17971. (function (BABYLON) {
  17972. var Camera = /** @class */ (function (_super) {
  17973. __extends(Camera, _super);
  17974. function Camera(name, position, scene) {
  17975. var _this = _super.call(this, name, scene) || this;
  17976. /**
  17977. * The vector the camera should consider as up.
  17978. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  17979. */
  17980. _this.upVector = BABYLON.Vector3.Up();
  17981. _this.orthoLeft = null;
  17982. _this.orthoRight = null;
  17983. _this.orthoBottom = null;
  17984. _this.orthoTop = null;
  17985. /**
  17986. * FOV is set in Radians. (default is 0.8)
  17987. */
  17988. _this.fov = 0.8;
  17989. _this.minZ = 1;
  17990. _this.maxZ = 10000.0;
  17991. _this.inertia = 0.9;
  17992. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17993. _this.isIntermediate = false;
  17994. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17995. /**
  17996. * Restricts the camera to viewing objects with the same layerMask.
  17997. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  17998. */
  17999. _this.layerMask = 0x0FFFFFFF;
  18000. /**
  18001. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18002. */
  18003. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18004. // Camera rig members
  18005. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18006. _this._rigCameras = new Array();
  18007. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18008. _this._skipRendering = false;
  18009. _this.customRenderTargets = new Array();
  18010. // Observables
  18011. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18012. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18013. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18014. _this.onRestoreStateObservable = new BABYLON.Observable();
  18015. // Cache
  18016. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18017. _this._projectionMatrix = new BABYLON.Matrix();
  18018. _this._doNotComputeProjectionMatrix = false;
  18019. _this._postProcesses = new Array();
  18020. _this._transformMatrix = BABYLON.Matrix.Zero();
  18021. _this._activeMeshes = new BABYLON.SmartArray(256);
  18022. _this._globalPosition = BABYLON.Vector3.Zero();
  18023. _this._refreshFrustumPlanes = true;
  18024. _this.getScene().addCamera(_this);
  18025. if (!_this.getScene().activeCamera) {
  18026. _this.getScene().activeCamera = _this;
  18027. }
  18028. _this.position = position;
  18029. return _this;
  18030. }
  18031. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18032. get: function () {
  18033. return Camera._PERSPECTIVE_CAMERA;
  18034. },
  18035. enumerable: true,
  18036. configurable: true
  18037. });
  18038. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18039. get: function () {
  18040. return Camera._ORTHOGRAPHIC_CAMERA;
  18041. },
  18042. enumerable: true,
  18043. configurable: true
  18044. });
  18045. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18046. /**
  18047. * This is the default FOV mode for perspective cameras.
  18048. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18049. *
  18050. */
  18051. get: function () {
  18052. return Camera._FOVMODE_VERTICAL_FIXED;
  18053. },
  18054. enumerable: true,
  18055. configurable: true
  18056. });
  18057. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18058. /**
  18059. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18060. *
  18061. */
  18062. get: function () {
  18063. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18069. get: function () {
  18070. return Camera._RIG_MODE_NONE;
  18071. },
  18072. enumerable: true,
  18073. configurable: true
  18074. });
  18075. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18076. get: function () {
  18077. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18078. },
  18079. enumerable: true,
  18080. configurable: true
  18081. });
  18082. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18083. get: function () {
  18084. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18085. },
  18086. enumerable: true,
  18087. configurable: true
  18088. });
  18089. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18090. get: function () {
  18091. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18092. },
  18093. enumerable: true,
  18094. configurable: true
  18095. });
  18096. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18097. get: function () {
  18098. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18099. },
  18100. enumerable: true,
  18101. configurable: true
  18102. });
  18103. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18104. get: function () {
  18105. return Camera._RIG_MODE_VR;
  18106. },
  18107. enumerable: true,
  18108. configurable: true
  18109. });
  18110. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18111. get: function () {
  18112. return Camera._RIG_MODE_WEBVR;
  18113. },
  18114. enumerable: true,
  18115. configurable: true
  18116. });
  18117. /**
  18118. * Store current camera state (fov, position, etc..)
  18119. */
  18120. Camera.prototype.storeState = function () {
  18121. this._stateStored = true;
  18122. this._storedFov = this.fov;
  18123. return this;
  18124. };
  18125. /**
  18126. * Restores the camera state values if it has been stored. You must call storeState() first
  18127. */
  18128. Camera.prototype._restoreStateValues = function () {
  18129. if (!this._stateStored) {
  18130. return false;
  18131. }
  18132. this.fov = this._storedFov;
  18133. return true;
  18134. };
  18135. /**
  18136. * Restored camera state. You must call storeState() first
  18137. */
  18138. Camera.prototype.restoreState = function () {
  18139. if (this._restoreStateValues()) {
  18140. this.onRestoreStateObservable.notifyObservers(this);
  18141. return true;
  18142. }
  18143. return false;
  18144. };
  18145. Camera.prototype.getClassName = function () {
  18146. return "Camera";
  18147. };
  18148. /**
  18149. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18150. */
  18151. Camera.prototype.toString = function (fullDetails) {
  18152. var ret = "Name: " + this.name;
  18153. ret += ", type: " + this.getClassName();
  18154. if (this.animations) {
  18155. for (var i = 0; i < this.animations.length; i++) {
  18156. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18157. }
  18158. }
  18159. if (fullDetails) {
  18160. }
  18161. return ret;
  18162. };
  18163. Object.defineProperty(Camera.prototype, "globalPosition", {
  18164. get: function () {
  18165. return this._globalPosition;
  18166. },
  18167. enumerable: true,
  18168. configurable: true
  18169. });
  18170. Camera.prototype.getActiveMeshes = function () {
  18171. return this._activeMeshes;
  18172. };
  18173. Camera.prototype.isActiveMesh = function (mesh) {
  18174. return (this._activeMeshes.indexOf(mesh) !== -1);
  18175. };
  18176. //Cache
  18177. Camera.prototype._initCache = function () {
  18178. _super.prototype._initCache.call(this);
  18179. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18180. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18181. this._cache.mode = undefined;
  18182. this._cache.minZ = undefined;
  18183. this._cache.maxZ = undefined;
  18184. this._cache.fov = undefined;
  18185. this._cache.fovMode = undefined;
  18186. this._cache.aspectRatio = undefined;
  18187. this._cache.orthoLeft = undefined;
  18188. this._cache.orthoRight = undefined;
  18189. this._cache.orthoBottom = undefined;
  18190. this._cache.orthoTop = undefined;
  18191. this._cache.renderWidth = undefined;
  18192. this._cache.renderHeight = undefined;
  18193. };
  18194. Camera.prototype._updateCache = function (ignoreParentClass) {
  18195. if (!ignoreParentClass) {
  18196. _super.prototype._updateCache.call(this);
  18197. }
  18198. this._cache.position.copyFrom(this.position);
  18199. this._cache.upVector.copyFrom(this.upVector);
  18200. };
  18201. // Synchronized
  18202. Camera.prototype._isSynchronized = function () {
  18203. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18204. };
  18205. Camera.prototype._isSynchronizedViewMatrix = function () {
  18206. if (!_super.prototype._isSynchronized.call(this))
  18207. return false;
  18208. return this._cache.position.equals(this.position)
  18209. && this._cache.upVector.equals(this.upVector)
  18210. && this.isSynchronizedWithParent();
  18211. };
  18212. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18213. var check = this._cache.mode === this.mode
  18214. && this._cache.minZ === this.minZ
  18215. && this._cache.maxZ === this.maxZ;
  18216. if (!check) {
  18217. return false;
  18218. }
  18219. var engine = this.getEngine();
  18220. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18221. check = this._cache.fov === this.fov
  18222. && this._cache.fovMode === this.fovMode
  18223. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18224. }
  18225. else {
  18226. check = this._cache.orthoLeft === this.orthoLeft
  18227. && this._cache.orthoRight === this.orthoRight
  18228. && this._cache.orthoBottom === this.orthoBottom
  18229. && this._cache.orthoTop === this.orthoTop
  18230. && this._cache.renderWidth === engine.getRenderWidth()
  18231. && this._cache.renderHeight === engine.getRenderHeight();
  18232. }
  18233. return check;
  18234. };
  18235. // Controls
  18236. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18237. };
  18238. Camera.prototype.detachControl = function (element) {
  18239. };
  18240. Camera.prototype.update = function () {
  18241. this._checkInputs();
  18242. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18243. this._updateRigCameras();
  18244. }
  18245. };
  18246. Camera.prototype._checkInputs = function () {
  18247. this.onAfterCheckInputsObservable.notifyObservers(this);
  18248. };
  18249. Object.defineProperty(Camera.prototype, "rigCameras", {
  18250. get: function () {
  18251. return this._rigCameras;
  18252. },
  18253. enumerable: true,
  18254. configurable: true
  18255. });
  18256. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18257. get: function () {
  18258. return this._rigPostProcess;
  18259. },
  18260. enumerable: true,
  18261. configurable: true
  18262. });
  18263. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18264. // invalidate framebuffer
  18265. if (this._postProcesses.length > 0) {
  18266. this._postProcesses[0].markTextureDirty();
  18267. }
  18268. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18269. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18270. var cam = this._rigCameras[i];
  18271. var rigPostProcess = cam._rigPostProcess;
  18272. // for VR rig, there does not have to be a post process
  18273. if (rigPostProcess) {
  18274. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18275. if (isPass) {
  18276. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18277. cam.isIntermediate = this._postProcesses.length === 0;
  18278. }
  18279. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18280. rigPostProcess.markTextureDirty();
  18281. }
  18282. else {
  18283. cam._postProcesses = this._postProcesses.slice(0);
  18284. }
  18285. }
  18286. };
  18287. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18288. if (insertAt === void 0) { insertAt = null; }
  18289. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18290. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18291. return 0;
  18292. }
  18293. if (insertAt == null || insertAt < 0) {
  18294. this._postProcesses.push(postProcess);
  18295. }
  18296. else {
  18297. this._postProcesses.splice(insertAt, 0, postProcess);
  18298. }
  18299. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18300. return this._postProcesses.indexOf(postProcess);
  18301. };
  18302. Camera.prototype.detachPostProcess = function (postProcess) {
  18303. var idx = this._postProcesses.indexOf(postProcess);
  18304. if (idx !== -1) {
  18305. this._postProcesses.splice(idx, 1);
  18306. }
  18307. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18308. };
  18309. Camera.prototype.getWorldMatrix = function () {
  18310. if (!this._worldMatrix) {
  18311. this._worldMatrix = BABYLON.Matrix.Identity();
  18312. }
  18313. var viewMatrix = this.getViewMatrix();
  18314. viewMatrix.invertToRef(this._worldMatrix);
  18315. return this._worldMatrix;
  18316. };
  18317. Camera.prototype._getViewMatrix = function () {
  18318. return BABYLON.Matrix.Identity();
  18319. };
  18320. Camera.prototype.getViewMatrix = function (force) {
  18321. if (!force && this._isSynchronizedViewMatrix()) {
  18322. return this._computedViewMatrix;
  18323. }
  18324. this.updateCache();
  18325. this._computedViewMatrix = this._getViewMatrix();
  18326. this._currentRenderId = this.getScene().getRenderId();
  18327. this._refreshFrustumPlanes = true;
  18328. if (!this.parent || !this.parent.getWorldMatrix) {
  18329. this._globalPosition.copyFrom(this.position);
  18330. }
  18331. else {
  18332. if (!this._worldMatrix) {
  18333. this._worldMatrix = BABYLON.Matrix.Identity();
  18334. }
  18335. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18336. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18337. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18338. this._computedViewMatrix.invert();
  18339. this._markSyncedWithParent();
  18340. }
  18341. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18342. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18343. }
  18344. this.onViewMatrixChangedObservable.notifyObservers(this);
  18345. return this._computedViewMatrix;
  18346. };
  18347. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18348. this._doNotComputeProjectionMatrix = true;
  18349. if (projection !== undefined) {
  18350. this._projectionMatrix = projection;
  18351. }
  18352. };
  18353. ;
  18354. Camera.prototype.unfreezeProjectionMatrix = function () {
  18355. this._doNotComputeProjectionMatrix = false;
  18356. };
  18357. ;
  18358. Camera.prototype.getProjectionMatrix = function (force) {
  18359. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18360. return this._projectionMatrix;
  18361. }
  18362. // Cache
  18363. this._cache.mode = this.mode;
  18364. this._cache.minZ = this.minZ;
  18365. this._cache.maxZ = this.maxZ;
  18366. // Matrix
  18367. this._refreshFrustumPlanes = true;
  18368. var engine = this.getEngine();
  18369. var scene = this.getScene();
  18370. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18371. this._cache.fov = this.fov;
  18372. this._cache.fovMode = this.fovMode;
  18373. this._cache.aspectRatio = engine.getAspectRatio(this);
  18374. if (this.minZ <= 0) {
  18375. this.minZ = 0.1;
  18376. }
  18377. if (scene.useRightHandedSystem) {
  18378. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18379. }
  18380. else {
  18381. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18382. }
  18383. }
  18384. else {
  18385. var halfWidth = engine.getRenderWidth() / 2.0;
  18386. var halfHeight = engine.getRenderHeight() / 2.0;
  18387. if (scene.useRightHandedSystem) {
  18388. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18389. }
  18390. else {
  18391. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18392. }
  18393. this._cache.orthoLeft = this.orthoLeft;
  18394. this._cache.orthoRight = this.orthoRight;
  18395. this._cache.orthoBottom = this.orthoBottom;
  18396. this._cache.orthoTop = this.orthoTop;
  18397. this._cache.renderWidth = engine.getRenderWidth();
  18398. this._cache.renderHeight = engine.getRenderHeight();
  18399. }
  18400. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18401. return this._projectionMatrix;
  18402. };
  18403. Camera.prototype.getTranformationMatrix = function () {
  18404. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18405. return this._transformMatrix;
  18406. };
  18407. Camera.prototype.updateFrustumPlanes = function () {
  18408. if (!this._refreshFrustumPlanes) {
  18409. return;
  18410. }
  18411. this.getTranformationMatrix();
  18412. if (!this._frustumPlanes) {
  18413. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18414. }
  18415. else {
  18416. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18417. }
  18418. this._refreshFrustumPlanes = false;
  18419. };
  18420. Camera.prototype.isInFrustum = function (target) {
  18421. this.updateFrustumPlanes();
  18422. return target.isInFrustum(this._frustumPlanes);
  18423. };
  18424. Camera.prototype.isCompletelyInFrustum = function (target) {
  18425. this.updateFrustumPlanes();
  18426. return target.isCompletelyInFrustum(this._frustumPlanes);
  18427. };
  18428. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18429. if (length === void 0) { length = 100; }
  18430. if (!transform) {
  18431. transform = this.getWorldMatrix();
  18432. }
  18433. if (!origin) {
  18434. origin = this.position;
  18435. }
  18436. var forward = new BABYLON.Vector3(0, 0, 1);
  18437. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18438. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18439. return new BABYLON.Ray(origin, direction, length);
  18440. };
  18441. Camera.prototype.dispose = function () {
  18442. // Observables
  18443. this.onViewMatrixChangedObservable.clear();
  18444. this.onProjectionMatrixChangedObservable.clear();
  18445. this.onAfterCheckInputsObservable.clear();
  18446. this.onRestoreStateObservable.clear();
  18447. // Inputs
  18448. if (this.inputs) {
  18449. this.inputs.clear();
  18450. }
  18451. // Animations
  18452. this.getScene().stopAnimation(this);
  18453. // Remove from scene
  18454. this.getScene().removeCamera(this);
  18455. while (this._rigCameras.length > 0) {
  18456. var camera = this._rigCameras.pop();
  18457. if (camera) {
  18458. camera.dispose();
  18459. }
  18460. }
  18461. // Postprocesses
  18462. if (this._rigPostProcess) {
  18463. this._rigPostProcess.dispose(this);
  18464. this._rigPostProcess = null;
  18465. this._postProcesses = [];
  18466. }
  18467. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18468. this._rigPostProcess = null;
  18469. this._postProcesses = [];
  18470. }
  18471. else {
  18472. var i = this._postProcesses.length;
  18473. while (--i >= 0) {
  18474. this._postProcesses[i].dispose(this);
  18475. }
  18476. }
  18477. // Render targets
  18478. var i = this.customRenderTargets.length;
  18479. while (--i >= 0) {
  18480. this.customRenderTargets[i].dispose();
  18481. }
  18482. this.customRenderTargets = [];
  18483. // Active Meshes
  18484. this._activeMeshes.dispose();
  18485. _super.prototype.dispose.call(this);
  18486. };
  18487. Object.defineProperty(Camera.prototype, "leftCamera", {
  18488. // ---- Camera rigs section ----
  18489. get: function () {
  18490. if (this._rigCameras.length < 1) {
  18491. return null;
  18492. }
  18493. return this._rigCameras[0];
  18494. },
  18495. enumerable: true,
  18496. configurable: true
  18497. });
  18498. Object.defineProperty(Camera.prototype, "rightCamera", {
  18499. get: function () {
  18500. if (this._rigCameras.length < 2) {
  18501. return null;
  18502. }
  18503. return this._rigCameras[1];
  18504. },
  18505. enumerable: true,
  18506. configurable: true
  18507. });
  18508. Camera.prototype.getLeftTarget = function () {
  18509. if (this._rigCameras.length < 1) {
  18510. return null;
  18511. }
  18512. return this._rigCameras[0].getTarget();
  18513. };
  18514. Camera.prototype.getRightTarget = function () {
  18515. if (this._rigCameras.length < 2) {
  18516. return null;
  18517. }
  18518. return this._rigCameras[1].getTarget();
  18519. };
  18520. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18521. if (this.cameraRigMode === mode) {
  18522. return;
  18523. }
  18524. while (this._rigCameras.length > 0) {
  18525. var camera = this._rigCameras.pop();
  18526. if (camera) {
  18527. camera.dispose();
  18528. }
  18529. }
  18530. this.cameraRigMode = mode;
  18531. this._cameraRigParams = {};
  18532. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18533. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18534. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18535. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18536. // create the rig cameras, unless none
  18537. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18538. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18539. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18540. if (leftCamera && rightCamera) {
  18541. this._rigCameras.push(leftCamera);
  18542. this._rigCameras.push(rightCamera);
  18543. }
  18544. }
  18545. switch (this.cameraRigMode) {
  18546. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18547. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18548. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18549. break;
  18550. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18551. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18552. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18553. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18554. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18555. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18556. break;
  18557. case Camera.RIG_MODE_VR:
  18558. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18559. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18560. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18561. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18562. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18563. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18564. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18565. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18566. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18567. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18568. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18569. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18570. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18571. if (metrics.compensateDistortion) {
  18572. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18573. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18574. }
  18575. break;
  18576. case Camera.RIG_MODE_WEBVR:
  18577. if (rigParams.vrDisplay) {
  18578. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18579. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18580. //Left eye
  18581. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18582. this._rigCameras[0].setCameraRigParameter("left", true);
  18583. //leaving this for future reference
  18584. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18585. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18586. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18587. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18588. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18589. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18590. this._rigCameras[0].parent = this;
  18591. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18592. //Right eye
  18593. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18594. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18595. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18596. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18597. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18598. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18599. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18600. this._rigCameras[1].parent = this;
  18601. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18602. if (Camera.UseAlternateWebVRRendering) {
  18603. this._rigCameras[1]._skipRendering = true;
  18604. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18605. }
  18606. }
  18607. break;
  18608. }
  18609. this._cascadePostProcessesToRigCams();
  18610. this.update();
  18611. };
  18612. Camera.prototype._getVRProjectionMatrix = function () {
  18613. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18614. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18615. return this._projectionMatrix;
  18616. };
  18617. Camera.prototype._updateCameraRotationMatrix = function () {
  18618. //Here for WebVR
  18619. };
  18620. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18621. //Here for WebVR
  18622. };
  18623. /**
  18624. * This function MUST be overwritten by the different WebVR cameras available.
  18625. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18626. */
  18627. Camera.prototype._getWebVRProjectionMatrix = function () {
  18628. return BABYLON.Matrix.Identity();
  18629. };
  18630. /**
  18631. * This function MUST be overwritten by the different WebVR cameras available.
  18632. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18633. */
  18634. Camera.prototype._getWebVRViewMatrix = function () {
  18635. return BABYLON.Matrix.Identity();
  18636. };
  18637. Camera.prototype.setCameraRigParameter = function (name, value) {
  18638. if (!this._cameraRigParams) {
  18639. this._cameraRigParams = {};
  18640. }
  18641. this._cameraRigParams[name] = value;
  18642. //provisionnally:
  18643. if (name === "interaxialDistance") {
  18644. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18645. }
  18646. };
  18647. /**
  18648. * needs to be overridden by children so sub has required properties to be copied
  18649. */
  18650. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18651. return null;
  18652. };
  18653. /**
  18654. * May need to be overridden by children
  18655. */
  18656. Camera.prototype._updateRigCameras = function () {
  18657. for (var i = 0; i < this._rigCameras.length; i++) {
  18658. this._rigCameras[i].minZ = this.minZ;
  18659. this._rigCameras[i].maxZ = this.maxZ;
  18660. this._rigCameras[i].fov = this.fov;
  18661. }
  18662. // only update viewport when ANAGLYPH
  18663. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18664. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18665. }
  18666. };
  18667. Camera.prototype._setupInputs = function () {
  18668. };
  18669. Camera.prototype.serialize = function () {
  18670. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18671. // Type
  18672. serializationObject.type = this.getClassName();
  18673. // Parent
  18674. if (this.parent) {
  18675. serializationObject.parentId = this.parent.id;
  18676. }
  18677. if (this.inputs) {
  18678. this.inputs.serialize(serializationObject);
  18679. }
  18680. // Animations
  18681. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18682. serializationObject.ranges = this.serializeAnimationRanges();
  18683. return serializationObject;
  18684. };
  18685. Camera.prototype.clone = function (name) {
  18686. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18687. };
  18688. Camera.prototype.getDirection = function (localAxis) {
  18689. var result = BABYLON.Vector3.Zero();
  18690. this.getDirectionToRef(localAxis, result);
  18691. return result;
  18692. };
  18693. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18694. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18695. };
  18696. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18697. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18698. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18699. switch (type) {
  18700. case "ArcRotateCamera":
  18701. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18702. case "DeviceOrientationCamera":
  18703. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18704. case "FollowCamera":
  18705. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18706. case "ArcFollowCamera":
  18707. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18708. case "GamepadCamera":
  18709. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18710. case "TouchCamera":
  18711. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18712. case "VirtualJoysticksCamera":
  18713. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18714. case "WebVRFreeCamera":
  18715. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18716. case "WebVRGamepadCamera":
  18717. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18718. case "VRDeviceOrientationFreeCamera":
  18719. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18720. case "VRDeviceOrientationGamepadCamera":
  18721. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18722. case "AnaglyphArcRotateCamera":
  18723. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18724. case "AnaglyphFreeCamera":
  18725. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18726. case "AnaglyphGamepadCamera":
  18727. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18728. case "AnaglyphUniversalCamera":
  18729. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18730. case "StereoscopicArcRotateCamera":
  18731. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18732. case "StereoscopicFreeCamera":
  18733. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18734. case "StereoscopicGamepadCamera":
  18735. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18736. case "StereoscopicUniversalCamera":
  18737. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18738. case "FreeCamera":// Forcing Universal here
  18739. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18740. default:// Universal Camera is the default value
  18741. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18742. }
  18743. };
  18744. Camera.prototype.computeWorldMatrix = function () {
  18745. return this.getWorldMatrix();
  18746. };
  18747. Camera.Parse = function (parsedCamera, scene) {
  18748. var type = parsedCamera.type;
  18749. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18750. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18751. // Parent
  18752. if (parsedCamera.parentId) {
  18753. camera._waitingParentId = parsedCamera.parentId;
  18754. }
  18755. //If camera has an input manager, let it parse inputs settings
  18756. if (camera.inputs) {
  18757. camera.inputs.parse(parsedCamera);
  18758. camera._setupInputs();
  18759. }
  18760. if (camera.setPosition) {
  18761. camera.position.copyFromFloats(0, 0, 0);
  18762. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18763. }
  18764. // Target
  18765. if (parsedCamera.target) {
  18766. if (camera.setTarget) {
  18767. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18768. }
  18769. }
  18770. // Apply 3d rig, when found
  18771. if (parsedCamera.cameraRigMode) {
  18772. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18773. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18774. }
  18775. // Animations
  18776. if (parsedCamera.animations) {
  18777. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18778. var parsedAnimation = parsedCamera.animations[animationIndex];
  18779. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18780. }
  18781. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18782. }
  18783. if (parsedCamera.autoAnimate) {
  18784. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18785. }
  18786. return camera;
  18787. };
  18788. // Statics
  18789. Camera._PERSPECTIVE_CAMERA = 0;
  18790. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18791. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18792. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18793. Camera._RIG_MODE_NONE = 0;
  18794. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18795. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18796. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18797. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18798. Camera._RIG_MODE_VR = 20;
  18799. Camera._RIG_MODE_WEBVR = 21;
  18800. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18801. Camera.UseAlternateWebVRRendering = false;
  18802. __decorate([
  18803. BABYLON.serializeAsVector3()
  18804. ], Camera.prototype, "position", void 0);
  18805. __decorate([
  18806. BABYLON.serializeAsVector3()
  18807. ], Camera.prototype, "upVector", void 0);
  18808. __decorate([
  18809. BABYLON.serialize()
  18810. ], Camera.prototype, "orthoLeft", void 0);
  18811. __decorate([
  18812. BABYLON.serialize()
  18813. ], Camera.prototype, "orthoRight", void 0);
  18814. __decorate([
  18815. BABYLON.serialize()
  18816. ], Camera.prototype, "orthoBottom", void 0);
  18817. __decorate([
  18818. BABYLON.serialize()
  18819. ], Camera.prototype, "orthoTop", void 0);
  18820. __decorate([
  18821. BABYLON.serialize()
  18822. ], Camera.prototype, "fov", void 0);
  18823. __decorate([
  18824. BABYLON.serialize()
  18825. ], Camera.prototype, "minZ", void 0);
  18826. __decorate([
  18827. BABYLON.serialize()
  18828. ], Camera.prototype, "maxZ", void 0);
  18829. __decorate([
  18830. BABYLON.serialize()
  18831. ], Camera.prototype, "inertia", void 0);
  18832. __decorate([
  18833. BABYLON.serialize()
  18834. ], Camera.prototype, "mode", void 0);
  18835. __decorate([
  18836. BABYLON.serialize()
  18837. ], Camera.prototype, "layerMask", void 0);
  18838. __decorate([
  18839. BABYLON.serialize()
  18840. ], Camera.prototype, "fovMode", void 0);
  18841. __decorate([
  18842. BABYLON.serialize()
  18843. ], Camera.prototype, "cameraRigMode", void 0);
  18844. __decorate([
  18845. BABYLON.serialize()
  18846. ], Camera.prototype, "interaxialDistance", void 0);
  18847. __decorate([
  18848. BABYLON.serialize()
  18849. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18850. return Camera;
  18851. }(BABYLON.Node));
  18852. BABYLON.Camera = Camera;
  18853. })(BABYLON || (BABYLON = {}));
  18854. //# sourceMappingURL=babylon.camera.js.map
  18855. var BABYLON;
  18856. (function (BABYLON) {
  18857. var RenderingManager = /** @class */ (function () {
  18858. function RenderingManager(scene) {
  18859. this._renderingGroups = new Array();
  18860. this._autoClearDepthStencil = {};
  18861. this._customOpaqueSortCompareFn = {};
  18862. this._customAlphaTestSortCompareFn = {};
  18863. this._customTransparentSortCompareFn = {};
  18864. this._renderinGroupInfo = null;
  18865. this._scene = scene;
  18866. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18867. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18868. }
  18869. }
  18870. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18871. if (depth === void 0) { depth = true; }
  18872. if (stencil === void 0) { stencil = true; }
  18873. if (this._depthStencilBufferAlreadyCleaned) {
  18874. return;
  18875. }
  18876. this._scene.getEngine().clear(null, false, depth, stencil);
  18877. this._depthStencilBufferAlreadyCleaned = true;
  18878. };
  18879. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18880. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18881. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18882. var info = null;
  18883. if (observable) {
  18884. if (!this._renderinGroupInfo) {
  18885. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18886. }
  18887. info = this._renderinGroupInfo;
  18888. info.scene = this._scene;
  18889. info.camera = this._scene.activeCamera;
  18890. }
  18891. // Dispatch sprites
  18892. if (renderSprites) {
  18893. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18894. var manager = this._scene.spriteManagers[index];
  18895. this.dispatchSprites(manager);
  18896. }
  18897. }
  18898. // Render
  18899. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18900. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18901. var renderingGroup = this._renderingGroups[index];
  18902. if (!renderingGroup && !observable)
  18903. continue;
  18904. var renderingGroupMask = 0;
  18905. // Fire PRECLEAR stage
  18906. if (observable && info) {
  18907. renderingGroupMask = Math.pow(2, index);
  18908. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18909. info.renderingGroupId = index;
  18910. observable.notifyObservers(info, renderingGroupMask);
  18911. }
  18912. // Clear depth/stencil if needed
  18913. if (RenderingManager.AUTOCLEAR) {
  18914. var autoClear = this._autoClearDepthStencil[index];
  18915. if (autoClear && autoClear.autoClear) {
  18916. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18917. }
  18918. }
  18919. if (observable && info) {
  18920. // Fire PREOPAQUE stage
  18921. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18922. observable.notifyObservers(info, renderingGroupMask);
  18923. // Fire PRETRANSPARENT stage
  18924. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18925. observable.notifyObservers(info, renderingGroupMask);
  18926. }
  18927. if (renderingGroup)
  18928. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18929. // Fire POSTTRANSPARENT stage
  18930. if (observable && info) {
  18931. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18932. observable.notifyObservers(info, renderingGroupMask);
  18933. }
  18934. }
  18935. };
  18936. RenderingManager.prototype.reset = function () {
  18937. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18938. var renderingGroup = this._renderingGroups[index];
  18939. if (renderingGroup) {
  18940. renderingGroup.prepare();
  18941. }
  18942. }
  18943. };
  18944. RenderingManager.prototype.dispose = function () {
  18945. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18946. var renderingGroup = this._renderingGroups[index];
  18947. if (renderingGroup) {
  18948. renderingGroup.dispose();
  18949. }
  18950. }
  18951. this._renderingGroups.length = 0;
  18952. };
  18953. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18954. if (this._renderingGroups[renderingGroupId] === undefined) {
  18955. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18956. }
  18957. };
  18958. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18959. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18960. this._prepareRenderingGroup(renderingGroupId);
  18961. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18962. };
  18963. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18964. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18965. this._prepareRenderingGroup(renderingGroupId);
  18966. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18967. };
  18968. /**
  18969. * @param subMesh The submesh to dispatch
  18970. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18971. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18972. */
  18973. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18974. if (mesh === undefined) {
  18975. mesh = subMesh.getMesh();
  18976. }
  18977. var renderingGroupId = mesh.renderingGroupId || 0;
  18978. this._prepareRenderingGroup(renderingGroupId);
  18979. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18980. };
  18981. /**
  18982. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18983. * This allowed control for front to back rendering or reversly depending of the special needs.
  18984. *
  18985. * @param renderingGroupId The rendering group id corresponding to its index
  18986. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18987. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18988. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18989. */
  18990. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18991. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18992. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18993. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18994. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18995. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18996. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18997. if (this._renderingGroups[renderingGroupId]) {
  18998. var group = this._renderingGroups[renderingGroupId];
  18999. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19000. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19001. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19002. }
  19003. };
  19004. /**
  19005. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19006. *
  19007. * @param renderingGroupId The rendering group id corresponding to its index
  19008. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19009. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19010. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19011. */
  19012. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19013. if (depth === void 0) { depth = true; }
  19014. if (stencil === void 0) { stencil = true; }
  19015. this._autoClearDepthStencil[renderingGroupId] = {
  19016. autoClear: autoClearDepthStencil,
  19017. depth: depth,
  19018. stencil: stencil
  19019. };
  19020. };
  19021. /**
  19022. * The max id used for rendering groups (not included)
  19023. */
  19024. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19025. /**
  19026. * The min id used for rendering groups (included)
  19027. */
  19028. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19029. /**
  19030. * Used to globally prevent autoclearing scenes.
  19031. */
  19032. RenderingManager.AUTOCLEAR = true;
  19033. return RenderingManager;
  19034. }());
  19035. BABYLON.RenderingManager = RenderingManager;
  19036. })(BABYLON || (BABYLON = {}));
  19037. //# sourceMappingURL=babylon.renderingManager.js.map
  19038. var BABYLON;
  19039. (function (BABYLON) {
  19040. var RenderingGroup = /** @class */ (function () {
  19041. /**
  19042. * Creates a new rendering group.
  19043. * @param index The rendering group index
  19044. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19045. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19046. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19047. */
  19048. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19049. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19050. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19051. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19052. this.index = index;
  19053. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19054. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19055. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19056. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19057. this._particleSystems = new BABYLON.SmartArray(256);
  19058. this._spriteManagers = new BABYLON.SmartArray(256);
  19059. this._edgesRenderers = new BABYLON.SmartArray(16);
  19060. this._scene = scene;
  19061. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19062. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19063. this.transparentSortCompareFn = transparentSortCompareFn;
  19064. }
  19065. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19066. /**
  19067. * Set the opaque sort comparison function.
  19068. * If null the sub meshes will be render in the order they were created
  19069. */
  19070. set: function (value) {
  19071. this._opaqueSortCompareFn = value;
  19072. if (value) {
  19073. this._renderOpaque = this.renderOpaqueSorted;
  19074. }
  19075. else {
  19076. this._renderOpaque = RenderingGroup.renderUnsorted;
  19077. }
  19078. },
  19079. enumerable: true,
  19080. configurable: true
  19081. });
  19082. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19083. /**
  19084. * Set the alpha test sort comparison function.
  19085. * If null the sub meshes will be render in the order they were created
  19086. */
  19087. set: function (value) {
  19088. this._alphaTestSortCompareFn = value;
  19089. if (value) {
  19090. this._renderAlphaTest = this.renderAlphaTestSorted;
  19091. }
  19092. else {
  19093. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19094. }
  19095. },
  19096. enumerable: true,
  19097. configurable: true
  19098. });
  19099. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19100. /**
  19101. * Set the transparent sort comparison function.
  19102. * If null the sub meshes will be render in the order they were created
  19103. */
  19104. set: function (value) {
  19105. if (value) {
  19106. this._transparentSortCompareFn = value;
  19107. }
  19108. else {
  19109. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19110. }
  19111. this._renderTransparent = this.renderTransparentSorted;
  19112. },
  19113. enumerable: true,
  19114. configurable: true
  19115. });
  19116. /**
  19117. * Render all the sub meshes contained in the group.
  19118. * @param customRenderFunction Used to override the default render behaviour of the group.
  19119. * @returns true if rendered some submeshes.
  19120. */
  19121. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19122. if (customRenderFunction) {
  19123. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19124. return;
  19125. }
  19126. var engine = this._scene.getEngine();
  19127. // Depth only
  19128. if (this._depthOnlySubMeshes.length !== 0) {
  19129. engine.setColorWrite(false);
  19130. this._renderAlphaTest(this._depthOnlySubMeshes);
  19131. engine.setColorWrite(true);
  19132. }
  19133. // Opaque
  19134. if (this._opaqueSubMeshes.length !== 0) {
  19135. this._renderOpaque(this._opaqueSubMeshes);
  19136. }
  19137. // Alpha test
  19138. if (this._alphaTestSubMeshes.length !== 0) {
  19139. this._renderAlphaTest(this._alphaTestSubMeshes);
  19140. }
  19141. var stencilState = engine.getStencilBuffer();
  19142. engine.setStencilBuffer(false);
  19143. // Sprites
  19144. if (renderSprites) {
  19145. this._renderSprites();
  19146. }
  19147. // Particles
  19148. if (renderParticles) {
  19149. this._renderParticles(activeMeshes);
  19150. }
  19151. if (this.onBeforeTransparentRendering) {
  19152. this.onBeforeTransparentRendering();
  19153. }
  19154. // Transparent
  19155. if (this._transparentSubMeshes.length !== 0) {
  19156. this._renderTransparent(this._transparentSubMeshes);
  19157. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19158. }
  19159. // Set back stencil to false in case it changes before the edge renderer.
  19160. engine.setStencilBuffer(false);
  19161. // Edges
  19162. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19163. this._edgesRenderers.data[edgesRendererIndex].render();
  19164. }
  19165. // Restore Stencil state.
  19166. engine.setStencilBuffer(stencilState);
  19167. };
  19168. /**
  19169. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19170. * @param subMeshes The submeshes to render
  19171. */
  19172. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19173. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19174. };
  19175. /**
  19176. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19177. * @param subMeshes The submeshes to render
  19178. */
  19179. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19180. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19181. };
  19182. /**
  19183. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19184. * @param subMeshes The submeshes to render
  19185. */
  19186. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19187. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19188. };
  19189. /**
  19190. * Renders the submeshes in a specified order.
  19191. * @param subMeshes The submeshes to sort before render
  19192. * @param sortCompareFn The comparison function use to sort
  19193. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19194. * @param transparent Specifies to activate blending if true
  19195. */
  19196. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19197. var subIndex = 0;
  19198. var subMesh;
  19199. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19200. for (; subIndex < subMeshes.length; subIndex++) {
  19201. subMesh = subMeshes.data[subIndex];
  19202. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19203. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19204. }
  19205. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19206. if (sortCompareFn) {
  19207. sortedArray.sort(sortCompareFn);
  19208. }
  19209. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19210. subMesh = sortedArray[subIndex];
  19211. if (transparent) {
  19212. var material = subMesh.getMaterial();
  19213. if (material && material.needDepthPrePass) {
  19214. var engine = material.getScene().getEngine();
  19215. engine.setColorWrite(false);
  19216. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19217. subMesh.render(false);
  19218. engine.setColorWrite(true);
  19219. }
  19220. }
  19221. subMesh.render(transparent);
  19222. }
  19223. };
  19224. /**
  19225. * Renders the submeshes in the order they were dispatched (no sort applied).
  19226. * @param subMeshes The submeshes to render
  19227. */
  19228. RenderingGroup.renderUnsorted = function (subMeshes) {
  19229. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19230. var submesh = subMeshes.data[subIndex];
  19231. submesh.render(false);
  19232. }
  19233. };
  19234. /**
  19235. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19236. * are rendered back to front if in the same alpha index.
  19237. *
  19238. * @param a The first submesh
  19239. * @param b The second submesh
  19240. * @returns The result of the comparison
  19241. */
  19242. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19243. // Alpha index first
  19244. if (a._alphaIndex > b._alphaIndex) {
  19245. return 1;
  19246. }
  19247. if (a._alphaIndex < b._alphaIndex) {
  19248. return -1;
  19249. }
  19250. // Then distance to camera
  19251. return RenderingGroup.backToFrontSortCompare(a, b);
  19252. };
  19253. /**
  19254. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19255. * are rendered back to front.
  19256. *
  19257. * @param a The first submesh
  19258. * @param b The second submesh
  19259. * @returns The result of the comparison
  19260. */
  19261. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19262. // Then distance to camera
  19263. if (a._distanceToCamera < b._distanceToCamera) {
  19264. return 1;
  19265. }
  19266. if (a._distanceToCamera > b._distanceToCamera) {
  19267. return -1;
  19268. }
  19269. return 0;
  19270. };
  19271. /**
  19272. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19273. * are rendered front to back (prevent overdraw).
  19274. *
  19275. * @param a The first submesh
  19276. * @param b The second submesh
  19277. * @returns The result of the comparison
  19278. */
  19279. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19280. // Then distance to camera
  19281. if (a._distanceToCamera < b._distanceToCamera) {
  19282. return -1;
  19283. }
  19284. if (a._distanceToCamera > b._distanceToCamera) {
  19285. return 1;
  19286. }
  19287. return 0;
  19288. };
  19289. /**
  19290. * Resets the different lists of submeshes to prepare a new frame.
  19291. */
  19292. RenderingGroup.prototype.prepare = function () {
  19293. this._opaqueSubMeshes.reset();
  19294. this._transparentSubMeshes.reset();
  19295. this._alphaTestSubMeshes.reset();
  19296. this._depthOnlySubMeshes.reset();
  19297. this._particleSystems.reset();
  19298. this._spriteManagers.reset();
  19299. this._edgesRenderers.reset();
  19300. };
  19301. RenderingGroup.prototype.dispose = function () {
  19302. this._opaqueSubMeshes.dispose();
  19303. this._transparentSubMeshes.dispose();
  19304. this._alphaTestSubMeshes.dispose();
  19305. this._depthOnlySubMeshes.dispose();
  19306. this._particleSystems.dispose();
  19307. this._spriteManagers.dispose();
  19308. this._edgesRenderers.dispose();
  19309. };
  19310. /**
  19311. * Inserts the submesh in its correct queue depending on its material.
  19312. * @param subMesh The submesh to dispatch
  19313. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19314. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19315. */
  19316. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19317. // Get mesh and materials if not provided
  19318. if (mesh === undefined) {
  19319. mesh = subMesh.getMesh();
  19320. }
  19321. if (material === undefined) {
  19322. material = subMesh.getMaterial();
  19323. }
  19324. if (material === null || material === undefined) {
  19325. return;
  19326. }
  19327. if (material.needAlphaBlendingForMesh(mesh)) {
  19328. this._transparentSubMeshes.push(subMesh);
  19329. }
  19330. else if (material.needAlphaTesting()) {
  19331. if (material.needDepthPrePass) {
  19332. this._depthOnlySubMeshes.push(subMesh);
  19333. }
  19334. this._alphaTestSubMeshes.push(subMesh);
  19335. }
  19336. else {
  19337. if (material.needDepthPrePass) {
  19338. this._depthOnlySubMeshes.push(subMesh);
  19339. }
  19340. this._opaqueSubMeshes.push(subMesh); // Opaque
  19341. }
  19342. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19343. this._edgesRenderers.push(mesh._edgesRenderer);
  19344. }
  19345. };
  19346. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19347. this._spriteManagers.push(spriteManager);
  19348. };
  19349. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19350. this._particleSystems.push(particleSystem);
  19351. };
  19352. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19353. if (this._particleSystems.length === 0) {
  19354. return;
  19355. }
  19356. // Particles
  19357. var activeCamera = this._scene.activeCamera;
  19358. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19359. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19360. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19361. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19362. continue;
  19363. }
  19364. var emitter = particleSystem.emitter;
  19365. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19366. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19367. }
  19368. }
  19369. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19370. };
  19371. RenderingGroup.prototype._renderSprites = function () {
  19372. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19373. return;
  19374. }
  19375. // Sprites
  19376. var activeCamera = this._scene.activeCamera;
  19377. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19378. for (var id = 0; id < this._spriteManagers.length; id++) {
  19379. var spriteManager = this._spriteManagers.data[id];
  19380. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19381. spriteManager.render();
  19382. }
  19383. }
  19384. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19385. };
  19386. return RenderingGroup;
  19387. }());
  19388. BABYLON.RenderingGroup = RenderingGroup;
  19389. })(BABYLON || (BABYLON = {}));
  19390. //# sourceMappingURL=babylon.renderingGroup.js.map
  19391. var BABYLON;
  19392. (function (BABYLON) {
  19393. var ClickInfo = /** @class */ (function () {
  19394. function ClickInfo() {
  19395. this._singleClick = false;
  19396. this._doubleClick = false;
  19397. this._hasSwiped = false;
  19398. this._ignore = false;
  19399. }
  19400. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19401. get: function () {
  19402. return this._singleClick;
  19403. },
  19404. set: function (b) {
  19405. this._singleClick = b;
  19406. },
  19407. enumerable: true,
  19408. configurable: true
  19409. });
  19410. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19411. get: function () {
  19412. return this._doubleClick;
  19413. },
  19414. set: function (b) {
  19415. this._doubleClick = b;
  19416. },
  19417. enumerable: true,
  19418. configurable: true
  19419. });
  19420. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19421. get: function () {
  19422. return this._hasSwiped;
  19423. },
  19424. set: function (b) {
  19425. this._hasSwiped = b;
  19426. },
  19427. enumerable: true,
  19428. configurable: true
  19429. });
  19430. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19431. get: function () {
  19432. return this._ignore;
  19433. },
  19434. set: function (b) {
  19435. this._ignore = b;
  19436. },
  19437. enumerable: true,
  19438. configurable: true
  19439. });
  19440. return ClickInfo;
  19441. }());
  19442. /**
  19443. * This class is used by the onRenderingGroupObservable
  19444. */
  19445. var RenderingGroupInfo = /** @class */ (function () {
  19446. function RenderingGroupInfo() {
  19447. }
  19448. /**
  19449. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19450. * This stage will be fired no matter what
  19451. */
  19452. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19453. /**
  19454. * Called before opaque object are rendered.
  19455. * This stage will be fired only if there's 3D Opaque content to render
  19456. */
  19457. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19458. /**
  19459. * Called after the opaque objects are rendered and before the transparent ones
  19460. * This stage will be fired only if there's 3D transparent content to render
  19461. */
  19462. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19463. /**
  19464. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19465. * This stage will be fired no matter what
  19466. */
  19467. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19468. return RenderingGroupInfo;
  19469. }());
  19470. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19471. /**
  19472. * Represents a scene to be rendered by the engine.
  19473. * @see http://doc.babylonjs.com/page.php?p=21911
  19474. */
  19475. var Scene = /** @class */ (function () {
  19476. /**
  19477. * @constructor
  19478. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19479. */
  19480. function Scene(engine) {
  19481. // Members
  19482. this.autoClear = true;
  19483. this.autoClearDepthAndStencil = true;
  19484. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19485. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19486. this.forceWireframe = false;
  19487. this._forcePointsCloud = false;
  19488. this.forceShowBoundingBoxes = false;
  19489. this.animationsEnabled = true;
  19490. this.useConstantAnimationDeltaTime = false;
  19491. this.constantlyUpdateMeshUnderPointer = false;
  19492. this.hoverCursor = "pointer";
  19493. this.defaultCursor = "";
  19494. /**
  19495. * This is used to call preventDefault() on pointer down
  19496. * in order to block unwanted artifacts like system double clicks
  19497. */
  19498. this.preventDefaultOnPointerDown = true;
  19499. // Metadata
  19500. this.metadata = null;
  19501. /**
  19502. * An event triggered when the scene is disposed.
  19503. * @type {BABYLON.Observable}
  19504. */
  19505. this.onDisposeObservable = new BABYLON.Observable();
  19506. /**
  19507. * An event triggered before rendering the scene (right after animations and physics)
  19508. * @type {BABYLON.Observable}
  19509. */
  19510. this.onBeforeRenderObservable = new BABYLON.Observable();
  19511. /**
  19512. * An event triggered after rendering the scene
  19513. * @type {BABYLON.Observable}
  19514. */
  19515. this.onAfterRenderObservable = new BABYLON.Observable();
  19516. /**
  19517. * An event triggered before animating the scene
  19518. * @type {BABYLON.Observable}
  19519. */
  19520. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19521. /**
  19522. * An event triggered after animations processing
  19523. * @type {BABYLON.Observable}
  19524. */
  19525. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19526. /**
  19527. * An event triggered before draw calls are ready to be sent
  19528. * @type {BABYLON.Observable}
  19529. */
  19530. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19531. /**
  19532. * An event triggered after draw calls have been sent
  19533. * @type {BABYLON.Observable}
  19534. */
  19535. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19536. /**
  19537. * An event triggered when physic simulation is about to be run
  19538. * @type {BABYLON.Observable}
  19539. */
  19540. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19541. /**
  19542. * An event triggered when physic simulation has been done
  19543. * @type {BABYLON.Observable}
  19544. */
  19545. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19546. /**
  19547. * An event triggered when the scene is ready
  19548. * @type {BABYLON.Observable}
  19549. */
  19550. this.onReadyObservable = new BABYLON.Observable();
  19551. /**
  19552. * An event triggered before rendering a camera
  19553. * @type {BABYLON.Observable}
  19554. */
  19555. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19556. /**
  19557. * An event triggered after rendering a camera
  19558. * @type {BABYLON.Observable}
  19559. */
  19560. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19561. /**
  19562. * An event triggered when active meshes evaluation is about to start
  19563. * @type {BABYLON.Observable}
  19564. */
  19565. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19566. /**
  19567. * An event triggered when active meshes evaluation is done
  19568. * @type {BABYLON.Observable}
  19569. */
  19570. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19571. /**
  19572. * An event triggered when particles rendering is about to start
  19573. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19574. * @type {BABYLON.Observable}
  19575. */
  19576. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19577. /**
  19578. * An event triggered when particles rendering is done
  19579. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19580. * @type {BABYLON.Observable}
  19581. */
  19582. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19583. /**
  19584. * An event triggered when sprites rendering is about to start
  19585. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19586. * @type {BABYLON.Observable}
  19587. */
  19588. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19589. /**
  19590. * An event triggered when sprites rendering is done
  19591. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19592. * @type {BABYLON.Observable}
  19593. */
  19594. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19595. /**
  19596. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19597. * @type {BABYLON.Observable}
  19598. */
  19599. this.onDataLoadedObservable = new BABYLON.Observable();
  19600. /**
  19601. * An event triggered when a camera is created
  19602. * @type {BABYLON.Observable}
  19603. */
  19604. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19605. /**
  19606. * An event triggered when a camera is removed
  19607. * @type {BABYLON.Observable}
  19608. */
  19609. this.onCameraRemovedObservable = new BABYLON.Observable();
  19610. /**
  19611. * An event triggered when a light is created
  19612. * @type {BABYLON.Observable}
  19613. */
  19614. this.onNewLightAddedObservable = new BABYLON.Observable();
  19615. /**
  19616. * An event triggered when a light is removed
  19617. * @type {BABYLON.Observable}
  19618. */
  19619. this.onLightRemovedObservable = new BABYLON.Observable();
  19620. /**
  19621. * An event triggered when a geometry is created
  19622. * @type {BABYLON.Observable}
  19623. */
  19624. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19625. /**
  19626. * An event triggered when a geometry is removed
  19627. * @type {BABYLON.Observable}
  19628. */
  19629. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19630. /**
  19631. * An event triggered when a transform node is created
  19632. * @type {BABYLON.Observable}
  19633. */
  19634. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19635. /**
  19636. * An event triggered when a transform node is removed
  19637. * @type {BABYLON.Observable}
  19638. */
  19639. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19640. /**
  19641. * An event triggered when a mesh is created
  19642. * @type {BABYLON.Observable}
  19643. */
  19644. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19645. /**
  19646. * An event triggered when a mesh is removed
  19647. * @type {BABYLON.Observable}
  19648. */
  19649. this.onMeshRemovedObservable = new BABYLON.Observable();
  19650. /**
  19651. * An event triggered when render targets are about to be rendered
  19652. * Can happen multiple times per frame.
  19653. * @type {BABYLON.Observable}
  19654. */
  19655. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19656. /**
  19657. * An event triggered when render targets were rendered.
  19658. * Can happen multiple times per frame.
  19659. * @type {BABYLON.Observable}
  19660. */
  19661. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19662. /**
  19663. * An event triggered before calculating deterministic simulation step
  19664. * @type {BABYLON.Observable}
  19665. */
  19666. this.onBeforeStepObservable = new BABYLON.Observable();
  19667. /**
  19668. * An event triggered after calculating deterministic simulation step
  19669. * @type {BABYLON.Observable}
  19670. */
  19671. this.onAfterStepObservable = new BABYLON.Observable();
  19672. /**
  19673. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19674. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19675. * 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)
  19676. */
  19677. this.onRenderingGroupObservable = new BABYLON.Observable();
  19678. // Animations
  19679. this.animations = [];
  19680. /**
  19681. * 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).
  19682. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19683. */
  19684. this.onPrePointerObservable = new BABYLON.Observable();
  19685. /**
  19686. * Observable event triggered each time an input event is received from the rendering canvas
  19687. */
  19688. this.onPointerObservable = new BABYLON.Observable();
  19689. this._meshPickProceed = false;
  19690. this._currentPickResult = null;
  19691. this._previousPickResult = null;
  19692. this._totalPointersPressed = 0;
  19693. this._doubleClickOccured = false;
  19694. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19695. this.cameraToUseForPointers = null;
  19696. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19697. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19698. this._startingPointerTime = 0;
  19699. this._previousStartingPointerTime = 0;
  19700. // Deterministic lockstep
  19701. this._timeAccumulator = 0;
  19702. this._currentStepId = 0;
  19703. this._currentInternalStep = 0;
  19704. // Keyboard
  19705. /**
  19706. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19707. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19708. */
  19709. this.onPreKeyboardObservable = new BABYLON.Observable();
  19710. /**
  19711. * Observable event triggered each time an keyboard event is received from the hosting window
  19712. */
  19713. this.onKeyboardObservable = new BABYLON.Observable();
  19714. // Coordinate system
  19715. /**
  19716. * use right-handed coordinate system on this scene.
  19717. * @type {boolean}
  19718. */
  19719. this._useRightHandedSystem = false;
  19720. // Fog
  19721. this._fogEnabled = true;
  19722. this._fogMode = Scene.FOGMODE_NONE;
  19723. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19724. this.fogDensity = 0.1;
  19725. this.fogStart = 0;
  19726. this.fogEnd = 1000.0;
  19727. // Lights
  19728. /**
  19729. * is shadow enabled on this scene.
  19730. * @type {boolean}
  19731. */
  19732. this._shadowsEnabled = true;
  19733. /**
  19734. * is light enabled on this scene.
  19735. * @type {boolean}
  19736. */
  19737. this._lightsEnabled = true;
  19738. /**
  19739. * All of the lights added to this scene.
  19740. * @see BABYLON.Light
  19741. * @type {BABYLON.Light[]}
  19742. */
  19743. this.lights = new Array();
  19744. // Cameras
  19745. /** All of the cameras added to this scene. */
  19746. this.cameras = new Array();
  19747. /** All of the active cameras added to this scene. */
  19748. this.activeCameras = new Array();
  19749. // Meshes
  19750. /**
  19751. * All of the tranform nodes added to this scene.
  19752. * @see BABYLON.TransformNode
  19753. * @type {BABYLON.TransformNode[]}
  19754. */
  19755. this.transformNodes = new Array();
  19756. /**
  19757. * All of the (abstract) meshes added to this scene.
  19758. * @see BABYLON.AbstractMesh
  19759. * @type {BABYLON.AbstractMesh[]}
  19760. */
  19761. this.meshes = new Array();
  19762. /**
  19763. * All of the animation groups added to this scene.
  19764. * @see BABYLON.AnimationGroup
  19765. * @type {BABYLON.AnimationGroup[]}
  19766. */
  19767. this.animationGroups = new Array();
  19768. // Geometries
  19769. this._geometries = new Array();
  19770. this.materials = new Array();
  19771. this.multiMaterials = new Array();
  19772. // Textures
  19773. this._texturesEnabled = true;
  19774. this.textures = new Array();
  19775. // Particles
  19776. this.particlesEnabled = true;
  19777. this.particleSystems = new Array();
  19778. // Sprites
  19779. this.spritesEnabled = true;
  19780. this.spriteManagers = new Array();
  19781. // Layers
  19782. this.layers = new Array();
  19783. this.highlightLayers = new Array();
  19784. // Skeletons
  19785. this._skeletonsEnabled = true;
  19786. this.skeletons = new Array();
  19787. // Morph targets
  19788. this.morphTargetManagers = new Array();
  19789. // Lens flares
  19790. this.lensFlaresEnabled = true;
  19791. this.lensFlareSystems = new Array();
  19792. // Collisions
  19793. this.collisionsEnabled = true;
  19794. /** Defines the gravity applied to this scene */
  19795. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19796. // Postprocesses
  19797. this.postProcesses = new Array();
  19798. this.postProcessesEnabled = true;
  19799. // Customs render targets
  19800. this.renderTargetsEnabled = true;
  19801. this.dumpNextRenderTargets = false;
  19802. this.customRenderTargets = new Array();
  19803. // Imported meshes
  19804. this.importedMeshesFiles = new Array();
  19805. // Probes
  19806. this.probesEnabled = true;
  19807. this.reflectionProbes = new Array();
  19808. this._actionManagers = new Array();
  19809. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19810. // Procedural textures
  19811. this.proceduralTexturesEnabled = true;
  19812. this._proceduralTextures = new Array();
  19813. this.soundTracks = new Array();
  19814. this._audioEnabled = true;
  19815. this._headphone = false;
  19816. // Performance counters
  19817. this._totalVertices = new BABYLON.PerfCounter();
  19818. this._activeIndices = new BABYLON.PerfCounter();
  19819. this._activeParticles = new BABYLON.PerfCounter();
  19820. this._activeBones = new BABYLON.PerfCounter();
  19821. this._animationTime = 0;
  19822. this.animationTimeScale = 1;
  19823. this._renderId = 0;
  19824. this._executeWhenReadyTimeoutId = -1;
  19825. this._intermediateRendering = false;
  19826. this._viewUpdateFlag = -1;
  19827. this._projectionUpdateFlag = -1;
  19828. this._alternateViewUpdateFlag = -1;
  19829. this._alternateProjectionUpdateFlag = -1;
  19830. this._toBeDisposed = new BABYLON.SmartArray(256);
  19831. this._activeRequests = new Array();
  19832. this._pendingData = new Array();
  19833. this._isDisposed = false;
  19834. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19835. this._activeMeshes = new BABYLON.SmartArray(256);
  19836. this._processedMaterials = new BABYLON.SmartArray(256);
  19837. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19838. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19839. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19840. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19841. this._activeAnimatables = new Array();
  19842. this._transformMatrix = BABYLON.Matrix.Zero();
  19843. this._useAlternateCameraConfiguration = false;
  19844. this._alternateRendering = false;
  19845. this.requireLightSorting = false;
  19846. this._activeMeshesFrozen = false;
  19847. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19848. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19849. this._engine.scenes.push(this);
  19850. this._uid = null;
  19851. this._renderingManager = new BABYLON.RenderingManager(this);
  19852. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19853. if (BABYLON.OutlineRenderer) {
  19854. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19855. }
  19856. if (BABYLON.Tools.IsWindowObjectExist()) {
  19857. this.attachControl();
  19858. }
  19859. //simplification queue
  19860. if (BABYLON.SimplificationQueue) {
  19861. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19862. }
  19863. //collision coordinator initialization. For now legacy per default.
  19864. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19865. // Uniform Buffer
  19866. this._createUbo();
  19867. // Default Image processing definition.
  19868. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19869. }
  19870. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19871. /** The fog is deactivated */
  19872. get: function () {
  19873. return Scene._FOGMODE_NONE;
  19874. },
  19875. enumerable: true,
  19876. configurable: true
  19877. });
  19878. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19879. /** The fog density is following an exponential function */
  19880. get: function () {
  19881. return Scene._FOGMODE_EXP;
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19887. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19888. get: function () {
  19889. return Scene._FOGMODE_EXP2;
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19895. /** The fog density is following a linear function. */
  19896. get: function () {
  19897. return Scene._FOGMODE_LINEAR;
  19898. },
  19899. enumerable: true,
  19900. configurable: true
  19901. });
  19902. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19903. /**
  19904. * Texture used in all pbr material as the reflection texture.
  19905. * As in the majority of the scene they are the same (exception for multi room and so on),
  19906. * this is easier to reference from here than from all the materials.
  19907. */
  19908. get: function () {
  19909. return this._environmentTexture;
  19910. },
  19911. /**
  19912. * Texture used in all pbr material as the reflection texture.
  19913. * As in the majority of the scene they are the same (exception for multi room and so on),
  19914. * this is easier to set here than in all the materials.
  19915. */
  19916. set: function (value) {
  19917. if (this._environmentTexture === value) {
  19918. return;
  19919. }
  19920. this._environmentTexture = value;
  19921. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19922. },
  19923. enumerable: true,
  19924. configurable: true
  19925. });
  19926. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19927. /**
  19928. * Default image processing configuration used either in the rendering
  19929. * Forward main pass or through the imageProcessingPostProcess if present.
  19930. * As in the majority of the scene they are the same (exception for multi camera),
  19931. * this is easier to reference from here than from all the materials and post process.
  19932. *
  19933. * No setter as we it is a shared configuration, you can set the values instead.
  19934. */
  19935. get: function () {
  19936. return this._imageProcessingConfiguration;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19942. get: function () {
  19943. return this._forcePointsCloud;
  19944. },
  19945. set: function (value) {
  19946. if (this._forcePointsCloud === value) {
  19947. return;
  19948. }
  19949. this._forcePointsCloud = value;
  19950. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(Scene.prototype, "onDispose", {
  19956. /** A function to be executed when this scene is disposed. */
  19957. set: function (callback) {
  19958. if (this._onDisposeObserver) {
  19959. this.onDisposeObservable.remove(this._onDisposeObserver);
  19960. }
  19961. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. Object.defineProperty(Scene.prototype, "beforeRender", {
  19967. /** A function to be executed before rendering this scene */
  19968. set: function (callback) {
  19969. if (this._onBeforeRenderObserver) {
  19970. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19971. }
  19972. if (callback) {
  19973. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19974. }
  19975. },
  19976. enumerable: true,
  19977. configurable: true
  19978. });
  19979. Object.defineProperty(Scene.prototype, "afterRender", {
  19980. /** A function to be executed after rendering this scene */
  19981. set: function (callback) {
  19982. if (this._onAfterRenderObserver) {
  19983. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19984. }
  19985. if (callback) {
  19986. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19987. }
  19988. },
  19989. enumerable: true,
  19990. configurable: true
  19991. });
  19992. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19993. set: function (callback) {
  19994. if (this._onBeforeCameraRenderObserver) {
  19995. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19996. }
  19997. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20003. set: function (callback) {
  20004. if (this._onAfterCameraRenderObserver) {
  20005. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20006. }
  20007. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20008. },
  20009. enumerable: true,
  20010. configurable: true
  20011. });
  20012. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20013. get: function () {
  20014. if (!this._gamepadManager) {
  20015. this._gamepadManager = new BABYLON.GamepadManager(this);
  20016. }
  20017. return this._gamepadManager;
  20018. },
  20019. enumerable: true,
  20020. configurable: true
  20021. });
  20022. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20023. get: function () {
  20024. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20025. },
  20026. enumerable: true,
  20027. configurable: true
  20028. });
  20029. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20030. get: function () {
  20031. return this._useRightHandedSystem;
  20032. },
  20033. set: function (value) {
  20034. if (this._useRightHandedSystem === value) {
  20035. return;
  20036. }
  20037. this._useRightHandedSystem = value;
  20038. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. Scene.prototype.setStepId = function (newStepId) {
  20044. this._currentStepId = newStepId;
  20045. };
  20046. ;
  20047. Scene.prototype.getStepId = function () {
  20048. return this._currentStepId;
  20049. };
  20050. ;
  20051. Scene.prototype.getInternalStep = function () {
  20052. return this._currentInternalStep;
  20053. };
  20054. ;
  20055. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20056. get: function () {
  20057. return this._fogEnabled;
  20058. },
  20059. /**
  20060. * is fog enabled on this scene.
  20061. */
  20062. set: function (value) {
  20063. if (this._fogEnabled === value) {
  20064. return;
  20065. }
  20066. this._fogEnabled = value;
  20067. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20068. },
  20069. enumerable: true,
  20070. configurable: true
  20071. });
  20072. Object.defineProperty(Scene.prototype, "fogMode", {
  20073. get: function () {
  20074. return this._fogMode;
  20075. },
  20076. set: function (value) {
  20077. if (this._fogMode === value) {
  20078. return;
  20079. }
  20080. this._fogMode = value;
  20081. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20082. },
  20083. enumerable: true,
  20084. configurable: true
  20085. });
  20086. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20087. get: function () {
  20088. return this._shadowsEnabled;
  20089. },
  20090. set: function (value) {
  20091. if (this._shadowsEnabled === value) {
  20092. return;
  20093. }
  20094. this._shadowsEnabled = value;
  20095. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20096. },
  20097. enumerable: true,
  20098. configurable: true
  20099. });
  20100. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20101. get: function () {
  20102. return this._lightsEnabled;
  20103. },
  20104. set: function (value) {
  20105. if (this._lightsEnabled === value) {
  20106. return;
  20107. }
  20108. this._lightsEnabled = value;
  20109. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20110. },
  20111. enumerable: true,
  20112. configurable: true
  20113. });
  20114. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20115. /** The default material used on meshes when no material is affected */
  20116. get: function () {
  20117. if (!this._defaultMaterial) {
  20118. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20119. }
  20120. return this._defaultMaterial;
  20121. },
  20122. /** The default material used on meshes when no material is affected */
  20123. set: function (value) {
  20124. this._defaultMaterial = value;
  20125. },
  20126. enumerable: true,
  20127. configurable: true
  20128. });
  20129. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20130. get: function () {
  20131. return this._texturesEnabled;
  20132. },
  20133. set: function (value) {
  20134. if (this._texturesEnabled === value) {
  20135. return;
  20136. }
  20137. this._texturesEnabled = value;
  20138. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20144. get: function () {
  20145. return this._skeletonsEnabled;
  20146. },
  20147. set: function (value) {
  20148. if (this._skeletonsEnabled === value) {
  20149. return;
  20150. }
  20151. this._skeletonsEnabled = value;
  20152. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20158. get: function () {
  20159. if (!this._postProcessRenderPipelineManager) {
  20160. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20161. }
  20162. return this._postProcessRenderPipelineManager;
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20168. get: function () {
  20169. if (!this._mainSoundTrack) {
  20170. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20171. }
  20172. return this._mainSoundTrack;
  20173. },
  20174. enumerable: true,
  20175. configurable: true
  20176. });
  20177. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20178. get: function () {
  20179. return this._alternateRendering;
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20185. get: function () {
  20186. return this._frustumPlanes;
  20187. },
  20188. enumerable: true,
  20189. configurable: true
  20190. });
  20191. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20192. /**
  20193. * Gets the current geometry buffer associated to the scene.
  20194. */
  20195. get: function () {
  20196. return this._geometryBufferRenderer;
  20197. },
  20198. /**
  20199. * Sets the current geometry buffer for the scene.
  20200. */
  20201. set: function (geometryBufferRenderer) {
  20202. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20203. this._geometryBufferRenderer = geometryBufferRenderer;
  20204. }
  20205. },
  20206. enumerable: true,
  20207. configurable: true
  20208. });
  20209. Object.defineProperty(Scene.prototype, "debugLayer", {
  20210. // Properties
  20211. get: function () {
  20212. if (!this._debugLayer) {
  20213. this._debugLayer = new BABYLON.DebugLayer(this);
  20214. }
  20215. return this._debugLayer;
  20216. },
  20217. enumerable: true,
  20218. configurable: true
  20219. });
  20220. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20221. get: function () {
  20222. return this._workerCollisions;
  20223. },
  20224. set: function (enabled) {
  20225. if (!BABYLON.CollisionCoordinatorLegacy) {
  20226. return;
  20227. }
  20228. enabled = (enabled && !!Worker);
  20229. this._workerCollisions = enabled;
  20230. if (this.collisionCoordinator) {
  20231. this.collisionCoordinator.destroy();
  20232. }
  20233. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20234. this.collisionCoordinator.init(this);
  20235. },
  20236. enumerable: true,
  20237. configurable: true
  20238. });
  20239. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20240. get: function () {
  20241. return this._selectionOctree;
  20242. },
  20243. enumerable: true,
  20244. configurable: true
  20245. });
  20246. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20247. /**
  20248. * The mesh that is currently under the pointer.
  20249. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20250. */
  20251. get: function () {
  20252. return this._pointerOverMesh;
  20253. },
  20254. enumerable: true,
  20255. configurable: true
  20256. });
  20257. Object.defineProperty(Scene.prototype, "pointerX", {
  20258. /**
  20259. * Current on-screen X position of the pointer
  20260. * @return {number} X position of the pointer
  20261. */
  20262. get: function () {
  20263. return this._pointerX;
  20264. },
  20265. enumerable: true,
  20266. configurable: true
  20267. });
  20268. Object.defineProperty(Scene.prototype, "pointerY", {
  20269. /**
  20270. * Current on-screen Y position of the pointer
  20271. * @return {number} Y position of the pointer
  20272. */
  20273. get: function () {
  20274. return this._pointerY;
  20275. },
  20276. enumerable: true,
  20277. configurable: true
  20278. });
  20279. Scene.prototype.getCachedMaterial = function () {
  20280. return this._cachedMaterial;
  20281. };
  20282. Scene.prototype.getCachedEffect = function () {
  20283. return this._cachedEffect;
  20284. };
  20285. Scene.prototype.getCachedVisibility = function () {
  20286. return this._cachedVisibility;
  20287. };
  20288. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20289. if (visibility === void 0) { visibility = 1; }
  20290. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20291. };
  20292. Scene.prototype.getBoundingBoxRenderer = function () {
  20293. if (!this._boundingBoxRenderer) {
  20294. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20295. }
  20296. return this._boundingBoxRenderer;
  20297. };
  20298. Scene.prototype.getOutlineRenderer = function () {
  20299. return this._outlineRenderer;
  20300. };
  20301. Scene.prototype.getEngine = function () {
  20302. return this._engine;
  20303. };
  20304. Scene.prototype.getTotalVertices = function () {
  20305. return this._totalVertices.current;
  20306. };
  20307. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20308. get: function () {
  20309. return this._totalVertices;
  20310. },
  20311. enumerable: true,
  20312. configurable: true
  20313. });
  20314. Scene.prototype.getActiveIndices = function () {
  20315. return this._activeIndices.current;
  20316. };
  20317. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20318. get: function () {
  20319. return this._activeIndices;
  20320. },
  20321. enumerable: true,
  20322. configurable: true
  20323. });
  20324. Scene.prototype.getActiveParticles = function () {
  20325. return this._activeParticles.current;
  20326. };
  20327. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20328. get: function () {
  20329. return this._activeParticles;
  20330. },
  20331. enumerable: true,
  20332. configurable: true
  20333. });
  20334. Scene.prototype.getActiveBones = function () {
  20335. return this._activeBones.current;
  20336. };
  20337. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20338. get: function () {
  20339. return this._activeBones;
  20340. },
  20341. enumerable: true,
  20342. configurable: true
  20343. });
  20344. // Stats
  20345. Scene.prototype.getInterFramePerfCounter = function () {
  20346. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20347. return 0;
  20348. };
  20349. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20350. get: function () {
  20351. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20352. return null;
  20353. },
  20354. enumerable: true,
  20355. configurable: true
  20356. });
  20357. Scene.prototype.getLastFrameDuration = function () {
  20358. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20359. return 0;
  20360. };
  20361. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20362. get: function () {
  20363. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20364. return null;
  20365. },
  20366. enumerable: true,
  20367. configurable: true
  20368. });
  20369. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20370. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20371. return 0;
  20372. };
  20373. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20374. get: function () {
  20375. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20376. return null;
  20377. },
  20378. enumerable: true,
  20379. configurable: true
  20380. });
  20381. Scene.prototype.getActiveMeshes = function () {
  20382. return this._activeMeshes;
  20383. };
  20384. Scene.prototype.getRenderTargetsDuration = function () {
  20385. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20386. return 0;
  20387. };
  20388. Scene.prototype.getRenderDuration = function () {
  20389. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20390. return 0;
  20391. };
  20392. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20393. get: function () {
  20394. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20395. return null;
  20396. },
  20397. enumerable: true,
  20398. configurable: true
  20399. });
  20400. Scene.prototype.getParticlesDuration = function () {
  20401. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20402. return 0;
  20403. };
  20404. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20405. get: function () {
  20406. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20407. return null;
  20408. },
  20409. enumerable: true,
  20410. configurable: true
  20411. });
  20412. Scene.prototype.getSpritesDuration = function () {
  20413. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20414. return 0;
  20415. };
  20416. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20417. get: function () {
  20418. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20419. return null;
  20420. },
  20421. enumerable: true,
  20422. configurable: true
  20423. });
  20424. Scene.prototype.getAnimationRatio = function () {
  20425. return this._animationRatio;
  20426. };
  20427. Scene.prototype.getRenderId = function () {
  20428. return this._renderId;
  20429. };
  20430. Scene.prototype.incrementRenderId = function () {
  20431. this._renderId++;
  20432. };
  20433. Scene.prototype._updatePointerPosition = function (evt) {
  20434. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20435. if (!canvasRect) {
  20436. return;
  20437. }
  20438. this._pointerX = evt.clientX - canvasRect.left;
  20439. this._pointerY = evt.clientY - canvasRect.top;
  20440. this._unTranslatedPointerX = this._pointerX;
  20441. this._unTranslatedPointerY = this._pointerY;
  20442. };
  20443. Scene.prototype._createUbo = function () {
  20444. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20445. this._sceneUbo.addUniform("viewProjection", 16);
  20446. this._sceneUbo.addUniform("view", 16);
  20447. };
  20448. Scene.prototype._createAlternateUbo = function () {
  20449. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20450. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20451. this._alternateSceneUbo.addUniform("view", 16);
  20452. };
  20453. // Pointers handling
  20454. /**
  20455. * Use this method to simulate a pointer move on a mesh
  20456. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20457. */
  20458. Scene.prototype.simulatePointerMove = function (pickResult) {
  20459. var evt = new PointerEvent("pointermove");
  20460. return this._processPointerMove(pickResult, evt);
  20461. };
  20462. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20463. var canvas = this._engine.getRenderingCanvas();
  20464. if (!canvas) {
  20465. return this;
  20466. }
  20467. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20468. this.setPointerOverSprite(null);
  20469. this.setPointerOverMesh(pickResult.pickedMesh);
  20470. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20471. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20472. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20473. }
  20474. else {
  20475. canvas.style.cursor = this.hoverCursor;
  20476. }
  20477. }
  20478. else {
  20479. canvas.style.cursor = this.defaultCursor;
  20480. }
  20481. }
  20482. else {
  20483. this.setPointerOverMesh(null);
  20484. // Sprites
  20485. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20486. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20487. this.setPointerOverSprite(pickResult.pickedSprite);
  20488. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20489. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20490. }
  20491. else {
  20492. canvas.style.cursor = this.hoverCursor;
  20493. }
  20494. }
  20495. else {
  20496. this.setPointerOverSprite(null);
  20497. // Restore pointer
  20498. canvas.style.cursor = this.defaultCursor;
  20499. }
  20500. }
  20501. if (pickResult) {
  20502. if (this.onPointerMove) {
  20503. this.onPointerMove(evt, pickResult);
  20504. }
  20505. if (this.onPointerObservable.hasObservers()) {
  20506. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20507. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20508. this.onPointerObservable.notifyObservers(pi, type);
  20509. }
  20510. }
  20511. return this;
  20512. };
  20513. /**
  20514. * Use this method to simulate a pointer down on a mesh
  20515. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20516. */
  20517. Scene.prototype.simulatePointerDown = function (pickResult) {
  20518. var evt = new PointerEvent("pointerdown");
  20519. return this._processPointerDown(pickResult, evt);
  20520. };
  20521. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20522. var _this = this;
  20523. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20524. this._pickedDownMesh = pickResult.pickedMesh;
  20525. var actionManager = pickResult.pickedMesh.actionManager;
  20526. if (actionManager) {
  20527. if (actionManager.hasPickTriggers) {
  20528. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20529. switch (evt.button) {
  20530. case 0:
  20531. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20532. break;
  20533. case 1:
  20534. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20535. break;
  20536. case 2:
  20537. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20538. break;
  20539. }
  20540. }
  20541. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20542. window.setTimeout(function () {
  20543. 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);
  20544. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20545. if (_this._totalPointersPressed !== 0 &&
  20546. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20547. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20548. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20549. _this._startingPointerTime = 0;
  20550. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20551. }
  20552. }
  20553. }, Scene.LongPressDelay);
  20554. }
  20555. }
  20556. }
  20557. if (pickResult) {
  20558. if (this.onPointerDown) {
  20559. this.onPointerDown(evt, pickResult);
  20560. }
  20561. if (this.onPointerObservable.hasObservers()) {
  20562. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20563. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20564. this.onPointerObservable.notifyObservers(pi, type);
  20565. }
  20566. }
  20567. return this;
  20568. };
  20569. /**
  20570. * Use this method to simulate a pointer up on a mesh
  20571. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20572. */
  20573. Scene.prototype.simulatePointerUp = function (pickResult) {
  20574. var evt = new PointerEvent("pointerup");
  20575. var clickInfo = new ClickInfo();
  20576. clickInfo.singleClick = true;
  20577. clickInfo.ignore = true;
  20578. return this._processPointerUp(pickResult, evt, clickInfo);
  20579. };
  20580. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20581. if (pickResult && pickResult && pickResult.pickedMesh) {
  20582. this._pickedUpMesh = pickResult.pickedMesh;
  20583. if (this._pickedDownMesh === this._pickedUpMesh) {
  20584. if (this.onPointerPick) {
  20585. this.onPointerPick(evt, pickResult);
  20586. }
  20587. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20588. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20589. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20590. this.onPointerObservable.notifyObservers(pi, type);
  20591. }
  20592. }
  20593. if (pickResult.pickedMesh.actionManager) {
  20594. if (clickInfo.ignore) {
  20595. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20596. }
  20597. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20598. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20599. }
  20600. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20601. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20602. }
  20603. }
  20604. }
  20605. if (this._pickedDownMesh &&
  20606. this._pickedDownMesh.actionManager &&
  20607. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20608. this._pickedDownMesh !== this._pickedUpMesh) {
  20609. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20610. }
  20611. if (this.onPointerUp) {
  20612. this.onPointerUp(evt, pickResult);
  20613. }
  20614. if (this.onPointerObservable.hasObservers()) {
  20615. if (!clickInfo.ignore) {
  20616. if (!clickInfo.hasSwiped) {
  20617. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20618. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20619. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20620. this.onPointerObservable.notifyObservers(pi, type);
  20621. }
  20622. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20623. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20624. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20625. this.onPointerObservable.notifyObservers(pi, type);
  20626. }
  20627. }
  20628. }
  20629. else {
  20630. var type = BABYLON.PointerEventTypes.POINTERUP;
  20631. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20632. this.onPointerObservable.notifyObservers(pi, type);
  20633. }
  20634. }
  20635. return this;
  20636. };
  20637. /**
  20638. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20639. * @param attachUp defines if you want to attach events to pointerup
  20640. * @param attachDown defines if you want to attach events to pointerdown
  20641. * @param attachMove defines if you want to attach events to pointermove
  20642. */
  20643. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20644. var _this = this;
  20645. if (attachUp === void 0) { attachUp = true; }
  20646. if (attachDown === void 0) { attachDown = true; }
  20647. if (attachMove === void 0) { attachMove = true; }
  20648. this._initActionManager = function (act, clickInfo) {
  20649. if (!_this._meshPickProceed) {
  20650. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20651. _this._currentPickResult = pickResult;
  20652. if (pickResult) {
  20653. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20654. }
  20655. _this._meshPickProceed = true;
  20656. }
  20657. return act;
  20658. };
  20659. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20660. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20661. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20662. btn !== _this._previousButtonPressed) {
  20663. _this._doubleClickOccured = false;
  20664. clickInfo.singleClick = true;
  20665. clickInfo.ignore = false;
  20666. cb(clickInfo, _this._currentPickResult);
  20667. }
  20668. };
  20669. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20670. var clickInfo = new ClickInfo();
  20671. _this._currentPickResult = null;
  20672. var act = null;
  20673. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20674. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20675. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20676. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20677. act = _this._initActionManager(act, clickInfo);
  20678. if (act)
  20679. checkPicking = act.hasPickTriggers;
  20680. }
  20681. if (checkPicking) {
  20682. var btn = evt.button;
  20683. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20684. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20685. if (!clickInfo.hasSwiped) {
  20686. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20687. if (!checkSingleClickImmediately) {
  20688. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20689. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20690. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20691. act = _this._initActionManager(act, clickInfo);
  20692. if (act)
  20693. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20694. }
  20695. }
  20696. if (checkSingleClickImmediately) {
  20697. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20698. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20699. btn !== _this._previousButtonPressed) {
  20700. clickInfo.singleClick = true;
  20701. cb(clickInfo, _this._currentPickResult);
  20702. }
  20703. }
  20704. else {
  20705. // wait that no double click has been raised during the double click delay
  20706. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20707. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20708. }
  20709. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20710. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20711. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20712. act = _this._initActionManager(act, clickInfo);
  20713. if (act)
  20714. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20715. }
  20716. if (checkDoubleClick) {
  20717. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20718. if (btn === _this._previousButtonPressed &&
  20719. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20720. !_this._doubleClickOccured) {
  20721. // pointer has not moved for 2 clicks, it's a double click
  20722. if (!clickInfo.hasSwiped &&
  20723. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20724. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20725. _this._previousStartingPointerTime = 0;
  20726. _this._doubleClickOccured = true;
  20727. clickInfo.doubleClick = true;
  20728. clickInfo.ignore = false;
  20729. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20730. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20731. }
  20732. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20733. cb(clickInfo, _this._currentPickResult);
  20734. }
  20735. else {
  20736. _this._doubleClickOccured = false;
  20737. _this._previousStartingPointerTime = _this._startingPointerTime;
  20738. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20739. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20740. _this._previousButtonPressed = btn;
  20741. if (Scene.ExclusiveDoubleClickMode) {
  20742. if (_this._previousDelayedSimpleClickTimeout) {
  20743. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20744. }
  20745. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20746. cb(clickInfo, _this._previousPickResult);
  20747. }
  20748. else {
  20749. cb(clickInfo, _this._currentPickResult);
  20750. }
  20751. }
  20752. }
  20753. else {
  20754. _this._doubleClickOccured = false;
  20755. _this._previousStartingPointerTime = _this._startingPointerTime;
  20756. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20757. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20758. _this._previousButtonPressed = btn;
  20759. }
  20760. }
  20761. }
  20762. }
  20763. clickInfo.ignore = true;
  20764. cb(clickInfo, _this._currentPickResult);
  20765. };
  20766. this._spritePredicate = function (sprite) {
  20767. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20768. };
  20769. this._onPointerMove = function (evt) {
  20770. _this._updatePointerPosition(evt);
  20771. // PreObservable support
  20772. if (_this.onPrePointerObservable.hasObservers()) {
  20773. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20774. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20775. _this.onPrePointerObservable.notifyObservers(pi, type);
  20776. if (pi.skipOnPointerObservable) {
  20777. return;
  20778. }
  20779. }
  20780. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20781. return;
  20782. }
  20783. if (!_this.pointerMovePredicate) {
  20784. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20785. }
  20786. // Meshes
  20787. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20788. _this._processPointerMove(pickResult, evt);
  20789. };
  20790. this._onPointerDown = function (evt) {
  20791. _this._totalPointersPressed++;
  20792. _this._pickedDownMesh = null;
  20793. _this._meshPickProceed = false;
  20794. _this._updatePointerPosition(evt);
  20795. if (_this.preventDefaultOnPointerDown && canvas) {
  20796. evt.preventDefault();
  20797. canvas.focus();
  20798. }
  20799. // PreObservable support
  20800. if (_this.onPrePointerObservable.hasObservers()) {
  20801. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20802. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20803. _this.onPrePointerObservable.notifyObservers(pi, type);
  20804. if (pi.skipOnPointerObservable) {
  20805. return;
  20806. }
  20807. }
  20808. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20809. return;
  20810. }
  20811. _this._startingPointerPosition.x = _this._pointerX;
  20812. _this._startingPointerPosition.y = _this._pointerY;
  20813. _this._startingPointerTime = new Date().getTime();
  20814. if (!_this.pointerDownPredicate) {
  20815. _this.pointerDownPredicate = function (mesh) {
  20816. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20817. };
  20818. }
  20819. // Meshes
  20820. _this._pickedDownMesh = null;
  20821. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20822. _this._processPointerDown(pickResult, evt);
  20823. // Sprites
  20824. _this._pickedDownSprite = null;
  20825. if (_this.spriteManagers.length > 0) {
  20826. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20827. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20828. if (pickResult.pickedSprite.actionManager) {
  20829. _this._pickedDownSprite = pickResult.pickedSprite;
  20830. switch (evt.button) {
  20831. case 0:
  20832. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20833. break;
  20834. case 1:
  20835. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20836. break;
  20837. case 2:
  20838. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20839. break;
  20840. }
  20841. if (pickResult.pickedSprite.actionManager) {
  20842. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20843. }
  20844. }
  20845. }
  20846. }
  20847. };
  20848. this._onPointerUp = function (evt) {
  20849. if (_this._totalPointersPressed === 0) {
  20850. return; // So we need to test it the pointer down was pressed before.
  20851. }
  20852. _this._totalPointersPressed--;
  20853. _this._pickedUpMesh = null;
  20854. _this._meshPickProceed = false;
  20855. _this._updatePointerPosition(evt);
  20856. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20857. // PreObservable support
  20858. if (_this.onPrePointerObservable.hasObservers()) {
  20859. if (!clickInfo.ignore) {
  20860. if (!clickInfo.hasSwiped) {
  20861. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20862. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20863. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20864. _this.onPrePointerObservable.notifyObservers(pi, type);
  20865. if (pi.skipOnPointerObservable) {
  20866. return;
  20867. }
  20868. }
  20869. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20870. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20871. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20872. _this.onPrePointerObservable.notifyObservers(pi, type);
  20873. if (pi.skipOnPointerObservable) {
  20874. return;
  20875. }
  20876. }
  20877. }
  20878. }
  20879. else {
  20880. var type = BABYLON.PointerEventTypes.POINTERUP;
  20881. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20882. _this.onPrePointerObservable.notifyObservers(pi, type);
  20883. if (pi.skipOnPointerObservable) {
  20884. return;
  20885. }
  20886. }
  20887. }
  20888. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20889. return;
  20890. }
  20891. if (!_this.pointerUpPredicate) {
  20892. _this.pointerUpPredicate = function (mesh) {
  20893. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20894. };
  20895. }
  20896. // Meshes
  20897. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20898. _this._initActionManager(null, clickInfo);
  20899. }
  20900. if (!pickResult) {
  20901. pickResult = _this._currentPickResult;
  20902. }
  20903. _this._processPointerUp(pickResult, evt, clickInfo);
  20904. // Sprites
  20905. if (_this.spriteManagers.length > 0) {
  20906. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20907. if (spritePickResult) {
  20908. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20909. if (spritePickResult.pickedSprite.actionManager) {
  20910. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20911. if (spritePickResult.pickedSprite.actionManager) {
  20912. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20913. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20914. }
  20915. }
  20916. }
  20917. }
  20918. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20919. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20920. }
  20921. }
  20922. }
  20923. _this._previousPickResult = _this._currentPickResult;
  20924. });
  20925. };
  20926. this._onKeyDown = function (evt) {
  20927. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20928. if (_this.onPreKeyboardObservable.hasObservers()) {
  20929. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20930. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20931. if (pi.skipOnPointerObservable) {
  20932. return;
  20933. }
  20934. }
  20935. if (_this.onKeyboardObservable.hasObservers()) {
  20936. var pi = new BABYLON.KeyboardInfo(type, evt);
  20937. _this.onKeyboardObservable.notifyObservers(pi, type);
  20938. }
  20939. if (_this.actionManager) {
  20940. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20941. }
  20942. };
  20943. this._onKeyUp = function (evt) {
  20944. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20945. if (_this.onPreKeyboardObservable.hasObservers()) {
  20946. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20947. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20948. if (pi.skipOnPointerObservable) {
  20949. return;
  20950. }
  20951. }
  20952. if (_this.onKeyboardObservable.hasObservers()) {
  20953. var pi = new BABYLON.KeyboardInfo(type, evt);
  20954. _this.onKeyboardObservable.notifyObservers(pi, type);
  20955. }
  20956. if (_this.actionManager) {
  20957. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20958. }
  20959. };
  20960. var engine = this.getEngine();
  20961. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20962. if (!canvas) {
  20963. return;
  20964. }
  20965. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20966. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20967. });
  20968. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20969. if (!canvas) {
  20970. return;
  20971. }
  20972. canvas.removeEventListener("keydown", _this._onKeyDown);
  20973. canvas.removeEventListener("keyup", _this._onKeyUp);
  20974. });
  20975. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20976. var canvas = this._engine.getRenderingCanvas();
  20977. if (!canvas) {
  20978. return;
  20979. }
  20980. if (attachMove) {
  20981. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20982. // Wheel
  20983. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20984. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20985. }
  20986. if (attachDown) {
  20987. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20988. }
  20989. if (attachUp) {
  20990. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20991. }
  20992. canvas.tabIndex = 1;
  20993. };
  20994. Scene.prototype.detachControl = function () {
  20995. var engine = this.getEngine();
  20996. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20997. var canvas = engine.getRenderingCanvas();
  20998. if (!canvas) {
  20999. return;
  21000. }
  21001. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21002. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21003. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21004. if (this._onCanvasBlurObserver) {
  21005. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21006. }
  21007. if (this._onCanvasFocusObserver) {
  21008. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21009. }
  21010. // Wheel
  21011. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21012. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21013. // Keyboard
  21014. canvas.removeEventListener("keydown", this._onKeyDown);
  21015. canvas.removeEventListener("keyup", this._onKeyUp);
  21016. // Observables
  21017. this.onKeyboardObservable.clear();
  21018. this.onPreKeyboardObservable.clear();
  21019. this.onPointerObservable.clear();
  21020. this.onPrePointerObservable.clear();
  21021. };
  21022. /**
  21023. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21024. * Delay loaded resources are not taking in account
  21025. * @return true if all required resources are ready
  21026. */
  21027. Scene.prototype.isReady = function () {
  21028. if (this._isDisposed) {
  21029. return false;
  21030. }
  21031. if (this._pendingData.length > 0) {
  21032. return false;
  21033. }
  21034. var index;
  21035. var engine = this.getEngine();
  21036. // Geometries
  21037. for (index = 0; index < this._geometries.length; index++) {
  21038. var geometry = this._geometries[index];
  21039. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21040. return false;
  21041. }
  21042. }
  21043. // Meshes
  21044. for (index = 0; index < this.meshes.length; index++) {
  21045. var mesh = this.meshes[index];
  21046. if (!mesh.isEnabled()) {
  21047. continue;
  21048. }
  21049. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21050. continue;
  21051. }
  21052. if (!mesh.isReady()) {
  21053. return false;
  21054. }
  21055. // Highlight layers
  21056. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21057. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21058. var layer = _a[_i];
  21059. if (!layer.hasMesh(mesh)) {
  21060. continue;
  21061. }
  21062. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21063. var subMesh = _c[_b];
  21064. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21065. return false;
  21066. }
  21067. }
  21068. }
  21069. }
  21070. return true;
  21071. };
  21072. Scene.prototype.resetCachedMaterial = function () {
  21073. this._cachedMaterial = null;
  21074. this._cachedEffect = null;
  21075. this._cachedVisibility = null;
  21076. };
  21077. Scene.prototype.registerBeforeRender = function (func) {
  21078. this.onBeforeRenderObservable.add(func);
  21079. };
  21080. Scene.prototype.unregisterBeforeRender = function (func) {
  21081. this.onBeforeRenderObservable.removeCallback(func);
  21082. };
  21083. Scene.prototype.registerAfterRender = function (func) {
  21084. this.onAfterRenderObservable.add(func);
  21085. };
  21086. Scene.prototype.unregisterAfterRender = function (func) {
  21087. this.onAfterRenderObservable.removeCallback(func);
  21088. };
  21089. Scene.prototype._executeOnceBeforeRender = function (func) {
  21090. var _this = this;
  21091. var execFunc = function () {
  21092. func();
  21093. setTimeout(function () {
  21094. _this.unregisterBeforeRender(execFunc);
  21095. });
  21096. };
  21097. this.registerBeforeRender(execFunc);
  21098. };
  21099. /**
  21100. * The provided function will run before render once and will be disposed afterwards.
  21101. * A timeout delay can be provided so that the function will be executed in N ms.
  21102. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21103. * @param func The function to be executed.
  21104. * @param timeout optional delay in ms
  21105. */
  21106. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21107. var _this = this;
  21108. if (timeout !== undefined) {
  21109. setTimeout(function () {
  21110. _this._executeOnceBeforeRender(func);
  21111. }, timeout);
  21112. }
  21113. else {
  21114. this._executeOnceBeforeRender(func);
  21115. }
  21116. };
  21117. Scene.prototype._addPendingData = function (data) {
  21118. this._pendingData.push(data);
  21119. };
  21120. Scene.prototype._removePendingData = function (data) {
  21121. var wasLoading = this.isLoading;
  21122. var index = this._pendingData.indexOf(data);
  21123. if (index !== -1) {
  21124. this._pendingData.splice(index, 1);
  21125. }
  21126. if (wasLoading && !this.isLoading) {
  21127. this.onDataLoadedObservable.notifyObservers(this);
  21128. }
  21129. };
  21130. Scene.prototype.getWaitingItemsCount = function () {
  21131. return this._pendingData.length;
  21132. };
  21133. Object.defineProperty(Scene.prototype, "isLoading", {
  21134. get: function () {
  21135. return this._pendingData.length > 0;
  21136. },
  21137. enumerable: true,
  21138. configurable: true
  21139. });
  21140. /**
  21141. * Registers a function to be executed when the scene is ready.
  21142. * @param {Function} func - the function to be executed.
  21143. */
  21144. Scene.prototype.executeWhenReady = function (func) {
  21145. var _this = this;
  21146. this.onReadyObservable.add(func);
  21147. if (this._executeWhenReadyTimeoutId !== -1) {
  21148. return;
  21149. }
  21150. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21151. _this._checkIsReady();
  21152. }, 150);
  21153. };
  21154. Scene.prototype._checkIsReady = function () {
  21155. var _this = this;
  21156. if (this.isReady()) {
  21157. this.onReadyObservable.notifyObservers(this);
  21158. this.onReadyObservable.clear();
  21159. this._executeWhenReadyTimeoutId = -1;
  21160. return;
  21161. }
  21162. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21163. _this._checkIsReady();
  21164. }, 150);
  21165. };
  21166. // Animations
  21167. /**
  21168. * Will start the animation sequence of a given target
  21169. * @param target - the target
  21170. * @param {number} from - from which frame should animation start
  21171. * @param {number} to - till which frame should animation run.
  21172. * @param {boolean} [loop] - should the animation loop
  21173. * @param {number} [speedRatio] - the speed in which to run the animation
  21174. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21175. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21176. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21177. * See BABYLON.Animatable
  21178. */
  21179. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21180. if (speedRatio === void 0) { speedRatio = 1.0; }
  21181. if (from > to && speedRatio > 0) {
  21182. speedRatio *= -1;
  21183. }
  21184. this.stopAnimation(target);
  21185. if (!animatable) {
  21186. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21187. }
  21188. // Local animations
  21189. if (target.animations) {
  21190. animatable.appendAnimations(target, target.animations);
  21191. }
  21192. // Children animations
  21193. if (target.getAnimatables) {
  21194. var animatables = target.getAnimatables();
  21195. for (var index = 0; index < animatables.length; index++) {
  21196. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21197. }
  21198. }
  21199. animatable.reset();
  21200. return animatable;
  21201. };
  21202. /**
  21203. * Begin a new animation on a given node
  21204. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21205. * @param {BABYLON.Animation[]} defines the list of animations to start
  21206. * @param {number} from defines the initial value
  21207. * @param {number} to defines the final value
  21208. * @param {boolean} loop defines if you want animation to loop (off by default)
  21209. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21210. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21211. * @returns the list of created animatables
  21212. */
  21213. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21214. if (speedRatio === undefined) {
  21215. speedRatio = 1.0;
  21216. }
  21217. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21218. return animatable;
  21219. };
  21220. /**
  21221. * Begin a new animation on a given node and its hierarchy
  21222. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21223. * @param {boolean} 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.
  21224. * @param {BABYLON.Animation[]} defines the list of animations to start
  21225. * @param {number} from defines the initial value
  21226. * @param {number} to defines the final value
  21227. * @param {boolean} loop defines if you want animation to loop (off by default)
  21228. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21229. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21230. * @returns the list of animatables created for all nodes
  21231. */
  21232. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21233. var children = target.getDescendants(directDescendantsOnly);
  21234. var result = [];
  21235. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21236. var child = children_1[_i];
  21237. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21238. }
  21239. return result;
  21240. };
  21241. Scene.prototype.getAnimatableByTarget = function (target) {
  21242. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21243. if (this._activeAnimatables[index].target === target) {
  21244. return this._activeAnimatables[index];
  21245. }
  21246. }
  21247. return null;
  21248. };
  21249. Object.defineProperty(Scene.prototype, "animatables", {
  21250. get: function () {
  21251. return this._activeAnimatables;
  21252. },
  21253. enumerable: true,
  21254. configurable: true
  21255. });
  21256. /**
  21257. * Will stop the animation of the given target
  21258. * @param target - the target
  21259. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21260. * @see beginAnimation
  21261. */
  21262. Scene.prototype.stopAnimation = function (target, animationName) {
  21263. var animatable = this.getAnimatableByTarget(target);
  21264. if (animatable) {
  21265. animatable.stop(animationName);
  21266. }
  21267. };
  21268. /**
  21269. * Stops and removes all animations that have been applied to the scene
  21270. */
  21271. Scene.prototype.stopAllAnimations = function () {
  21272. if (this._activeAnimatables) {
  21273. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21274. this._activeAnimatables[i].stop();
  21275. }
  21276. this._activeAnimatables = [];
  21277. }
  21278. };
  21279. Scene.prototype._animate = function () {
  21280. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21281. return;
  21282. }
  21283. // Getting time
  21284. var now = BABYLON.Tools.Now;
  21285. if (!this._animationTimeLast) {
  21286. if (this._pendingData.length > 0) {
  21287. return;
  21288. }
  21289. this._animationTimeLast = now;
  21290. }
  21291. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21292. this._animationTime += deltaTime;
  21293. this._animationTimeLast = now;
  21294. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21295. this._activeAnimatables[index]._animate(this._animationTime);
  21296. }
  21297. };
  21298. // Matrix
  21299. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21300. this._useAlternateCameraConfiguration = active;
  21301. };
  21302. Scene.prototype.getViewMatrix = function () {
  21303. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21304. };
  21305. Scene.prototype.getProjectionMatrix = function () {
  21306. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21307. };
  21308. Scene.prototype.getTransformMatrix = function () {
  21309. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21310. };
  21311. Scene.prototype.setTransformMatrix = function (view, projection) {
  21312. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21313. return;
  21314. }
  21315. this._viewUpdateFlag = view.updateFlag;
  21316. this._projectionUpdateFlag = projection.updateFlag;
  21317. this._viewMatrix = view;
  21318. this._projectionMatrix = projection;
  21319. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21320. // Update frustum
  21321. if (!this._frustumPlanes) {
  21322. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21323. }
  21324. else {
  21325. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21326. }
  21327. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21328. var otherCamera = this.activeCamera._alternateCamera;
  21329. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21330. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21331. }
  21332. if (this._sceneUbo.useUbo) {
  21333. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21334. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21335. this._sceneUbo.update();
  21336. }
  21337. };
  21338. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21339. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21340. return;
  21341. }
  21342. this._alternateViewUpdateFlag = view.updateFlag;
  21343. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21344. this._alternateViewMatrix = view;
  21345. this._alternateProjectionMatrix = projection;
  21346. if (!this._alternateTransformMatrix) {
  21347. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21348. }
  21349. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21350. if (!this._alternateSceneUbo) {
  21351. this._createAlternateUbo();
  21352. }
  21353. if (this._alternateSceneUbo.useUbo) {
  21354. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21355. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21356. this._alternateSceneUbo.update();
  21357. }
  21358. };
  21359. Scene.prototype.getSceneUniformBuffer = function () {
  21360. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21361. };
  21362. // Methods
  21363. Scene.prototype.getUniqueId = function () {
  21364. var result = Scene._uniqueIdCounter;
  21365. Scene._uniqueIdCounter++;
  21366. return result;
  21367. };
  21368. Scene.prototype.addMesh = function (newMesh) {
  21369. this.meshes.push(newMesh);
  21370. //notify the collision coordinator
  21371. if (this.collisionCoordinator) {
  21372. this.collisionCoordinator.onMeshAdded(newMesh);
  21373. }
  21374. newMesh._resyncLightSources();
  21375. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21376. };
  21377. Scene.prototype.removeMesh = function (toRemove) {
  21378. var index = this.meshes.indexOf(toRemove);
  21379. if (index !== -1) {
  21380. // Remove from the scene if mesh found
  21381. this.meshes.splice(index, 1);
  21382. }
  21383. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21384. return index;
  21385. };
  21386. Scene.prototype.addTransformNode = function (newTransformNode) {
  21387. this.transformNodes.push(newTransformNode);
  21388. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21389. };
  21390. Scene.prototype.removeTransformNode = function (toRemove) {
  21391. var index = this.transformNodes.indexOf(toRemove);
  21392. if (index !== -1) {
  21393. // Remove from the scene if found
  21394. this.transformNodes.splice(index, 1);
  21395. }
  21396. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21397. return index;
  21398. };
  21399. Scene.prototype.removeSkeleton = function (toRemove) {
  21400. var index = this.skeletons.indexOf(toRemove);
  21401. if (index !== -1) {
  21402. // Remove from the scene if found
  21403. this.skeletons.splice(index, 1);
  21404. }
  21405. return index;
  21406. };
  21407. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21408. var index = this.morphTargetManagers.indexOf(toRemove);
  21409. if (index !== -1) {
  21410. // Remove from the scene if found
  21411. this.morphTargetManagers.splice(index, 1);
  21412. }
  21413. return index;
  21414. };
  21415. Scene.prototype.removeLight = function (toRemove) {
  21416. var index = this.lights.indexOf(toRemove);
  21417. if (index !== -1) {
  21418. // Remove from meshes
  21419. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21420. var mesh = _a[_i];
  21421. mesh._removeLightSource(toRemove);
  21422. }
  21423. // Remove from the scene if mesh found
  21424. this.lights.splice(index, 1);
  21425. this.sortLightsByPriority();
  21426. }
  21427. this.onLightRemovedObservable.notifyObservers(toRemove);
  21428. return index;
  21429. };
  21430. Scene.prototype.removeCamera = function (toRemove) {
  21431. var index = this.cameras.indexOf(toRemove);
  21432. if (index !== -1) {
  21433. // Remove from the scene if mesh found
  21434. this.cameras.splice(index, 1);
  21435. }
  21436. // Remove from activeCameras
  21437. var index2 = this.activeCameras.indexOf(toRemove);
  21438. if (index2 !== -1) {
  21439. // Remove from the scene if mesh found
  21440. this.activeCameras.splice(index2, 1);
  21441. }
  21442. // Reset the activeCamera
  21443. if (this.activeCamera === toRemove) {
  21444. if (this.cameras.length > 0) {
  21445. this.activeCamera = this.cameras[0];
  21446. }
  21447. else {
  21448. this.activeCamera = null;
  21449. }
  21450. }
  21451. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21452. return index;
  21453. };
  21454. Scene.prototype.removeParticleSystem = function (toRemove) {
  21455. var index = this.particleSystems.indexOf(toRemove);
  21456. if (index !== -1) {
  21457. this.particleSystems.splice(index, 1);
  21458. }
  21459. return index;
  21460. };
  21461. ;
  21462. Scene.prototype.removeAnimation = function (toRemove) {
  21463. var index = this.animations.indexOf(toRemove);
  21464. if (index !== -1) {
  21465. this.animations.splice(index, 1);
  21466. }
  21467. return index;
  21468. };
  21469. ;
  21470. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21471. var index = this.multiMaterials.indexOf(toRemove);
  21472. if (index !== -1) {
  21473. this.multiMaterials.splice(index, 1);
  21474. }
  21475. return index;
  21476. };
  21477. ;
  21478. Scene.prototype.removeMaterial = function (toRemove) {
  21479. var index = this.materials.indexOf(toRemove);
  21480. if (index !== -1) {
  21481. this.materials.splice(index, 1);
  21482. }
  21483. return index;
  21484. };
  21485. ;
  21486. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21487. var index = this.lensFlareSystems.indexOf(toRemove);
  21488. if (index !== -1) {
  21489. this.lensFlareSystems.splice(index, 1);
  21490. }
  21491. return index;
  21492. };
  21493. ;
  21494. Scene.prototype.removeActionManager = function (toRemove) {
  21495. var index = this._actionManagers.indexOf(toRemove);
  21496. if (index !== -1) {
  21497. this._actionManagers.splice(index, 1);
  21498. }
  21499. return index;
  21500. };
  21501. ;
  21502. Scene.prototype.addLight = function (newLight) {
  21503. this.lights.push(newLight);
  21504. this.sortLightsByPriority();
  21505. // Add light to all meshes (To support if the light is removed and then readded)
  21506. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21507. var mesh = _a[_i];
  21508. if (mesh._lightSources.indexOf(newLight) === -1) {
  21509. mesh._lightSources.push(newLight);
  21510. mesh._resyncLightSources();
  21511. }
  21512. }
  21513. this.onNewLightAddedObservable.notifyObservers(newLight);
  21514. };
  21515. Scene.prototype.sortLightsByPriority = function () {
  21516. if (this.requireLightSorting) {
  21517. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21518. }
  21519. };
  21520. Scene.prototype.addCamera = function (newCamera) {
  21521. this.cameras.push(newCamera);
  21522. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21523. };
  21524. Scene.prototype.addSkeleton = function (newSkeleton) {
  21525. this.skeletons.push(newSkeleton);
  21526. };
  21527. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21528. this.particleSystems.push(newParticleSystem);
  21529. };
  21530. Scene.prototype.addAnimation = function (newAnimation) {
  21531. this.animations.push(newAnimation);
  21532. };
  21533. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21534. this.multiMaterials.push(newMultiMaterial);
  21535. };
  21536. Scene.prototype.addMaterial = function (newMaterial) {
  21537. this.materials.push(newMaterial);
  21538. };
  21539. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21540. this.morphTargetManagers.push(newMorphTargetManager);
  21541. };
  21542. Scene.prototype.addGeometry = function (newGeometrie) {
  21543. this._geometries.push(newGeometrie);
  21544. };
  21545. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21546. this.lensFlareSystems.push(newLensFlareSystem);
  21547. };
  21548. Scene.prototype.addActionManager = function (newActionManager) {
  21549. this._actionManagers.push(newActionManager);
  21550. };
  21551. /**
  21552. * Switch active camera
  21553. * @param {Camera} newCamera - new active camera
  21554. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21555. */
  21556. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21557. if (attachControl === void 0) { attachControl = true; }
  21558. var canvas = this._engine.getRenderingCanvas();
  21559. if (!canvas) {
  21560. return;
  21561. }
  21562. if (this.activeCamera) {
  21563. this.activeCamera.detachControl(canvas);
  21564. }
  21565. this.activeCamera = newCamera;
  21566. if (attachControl) {
  21567. newCamera.attachControl(canvas);
  21568. }
  21569. };
  21570. /**
  21571. * sets the active camera of the scene using its ID
  21572. * @param {string} id - the camera's ID
  21573. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21574. * @see activeCamera
  21575. */
  21576. Scene.prototype.setActiveCameraByID = function (id) {
  21577. var camera = this.getCameraByID(id);
  21578. if (camera) {
  21579. this.activeCamera = camera;
  21580. return camera;
  21581. }
  21582. return null;
  21583. };
  21584. /**
  21585. * sets the active camera of the scene using its name
  21586. * @param {string} name - the camera's name
  21587. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21588. * @see activeCamera
  21589. */
  21590. Scene.prototype.setActiveCameraByName = function (name) {
  21591. var camera = this.getCameraByName(name);
  21592. if (camera) {
  21593. this.activeCamera = camera;
  21594. return camera;
  21595. }
  21596. return null;
  21597. };
  21598. /**
  21599. * get an animation group using its name
  21600. * @param {string} the material's name
  21601. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21602. */
  21603. Scene.prototype.getAnimationGroupByName = function (name) {
  21604. for (var index = 0; index < this.animationGroups.length; index++) {
  21605. if (this.animationGroups[index].name === name) {
  21606. return this.animationGroups[index];
  21607. }
  21608. }
  21609. return null;
  21610. };
  21611. /**
  21612. * get a material using its id
  21613. * @param {string} the material's ID
  21614. * @return {BABYLON.Material|null} the material or null if none found.
  21615. */
  21616. Scene.prototype.getMaterialByID = function (id) {
  21617. for (var index = 0; index < this.materials.length; index++) {
  21618. if (this.materials[index].id === id) {
  21619. return this.materials[index];
  21620. }
  21621. }
  21622. return null;
  21623. };
  21624. /**
  21625. * get a material using its name
  21626. * @param {string} the material's name
  21627. * @return {BABYLON.Material|null} the material or null if none found.
  21628. */
  21629. Scene.prototype.getMaterialByName = function (name) {
  21630. for (var index = 0; index < this.materials.length; index++) {
  21631. if (this.materials[index].name === name) {
  21632. return this.materials[index];
  21633. }
  21634. }
  21635. return null;
  21636. };
  21637. Scene.prototype.getLensFlareSystemByName = function (name) {
  21638. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21639. if (this.lensFlareSystems[index].name === name) {
  21640. return this.lensFlareSystems[index];
  21641. }
  21642. }
  21643. return null;
  21644. };
  21645. Scene.prototype.getLensFlareSystemByID = function (id) {
  21646. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21647. if (this.lensFlareSystems[index].id === id) {
  21648. return this.lensFlareSystems[index];
  21649. }
  21650. }
  21651. return null;
  21652. };
  21653. Scene.prototype.getCameraByID = function (id) {
  21654. for (var index = 0; index < this.cameras.length; index++) {
  21655. if (this.cameras[index].id === id) {
  21656. return this.cameras[index];
  21657. }
  21658. }
  21659. return null;
  21660. };
  21661. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21662. for (var index = 0; index < this.cameras.length; index++) {
  21663. if (this.cameras[index].uniqueId === uniqueId) {
  21664. return this.cameras[index];
  21665. }
  21666. }
  21667. return null;
  21668. };
  21669. /**
  21670. * get a camera using its name
  21671. * @param {string} the camera's name
  21672. * @return {BABYLON.Camera|null} the camera or null if none found.
  21673. */
  21674. Scene.prototype.getCameraByName = function (name) {
  21675. for (var index = 0; index < this.cameras.length; index++) {
  21676. if (this.cameras[index].name === name) {
  21677. return this.cameras[index];
  21678. }
  21679. }
  21680. return null;
  21681. };
  21682. /**
  21683. * get a bone using its id
  21684. * @param {string} the bone's id
  21685. * @return {BABYLON.Bone|null} the bone or null if not found
  21686. */
  21687. Scene.prototype.getBoneByID = function (id) {
  21688. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21689. var skeleton = this.skeletons[skeletonIndex];
  21690. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21691. if (skeleton.bones[boneIndex].id === id) {
  21692. return skeleton.bones[boneIndex];
  21693. }
  21694. }
  21695. }
  21696. return null;
  21697. };
  21698. /**
  21699. * get a bone using its id
  21700. * @param {string} the bone's name
  21701. * @return {BABYLON.Bone|null} the bone or null if not found
  21702. */
  21703. Scene.prototype.getBoneByName = function (name) {
  21704. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21705. var skeleton = this.skeletons[skeletonIndex];
  21706. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21707. if (skeleton.bones[boneIndex].name === name) {
  21708. return skeleton.bones[boneIndex];
  21709. }
  21710. }
  21711. }
  21712. return null;
  21713. };
  21714. /**
  21715. * get a light node using its name
  21716. * @param {string} the light's name
  21717. * @return {BABYLON.Light|null} the light or null if none found.
  21718. */
  21719. Scene.prototype.getLightByName = function (name) {
  21720. for (var index = 0; index < this.lights.length; index++) {
  21721. if (this.lights[index].name === name) {
  21722. return this.lights[index];
  21723. }
  21724. }
  21725. return null;
  21726. };
  21727. /**
  21728. * get a light node using its ID
  21729. * @param {string} the light's id
  21730. * @return {BABYLON.Light|null} the light or null if none found.
  21731. */
  21732. Scene.prototype.getLightByID = function (id) {
  21733. for (var index = 0; index < this.lights.length; index++) {
  21734. if (this.lights[index].id === id) {
  21735. return this.lights[index];
  21736. }
  21737. }
  21738. return null;
  21739. };
  21740. /**
  21741. * get a light node using its scene-generated unique ID
  21742. * @param {number} the light's unique id
  21743. * @return {BABYLON.Light|null} the light or null if none found.
  21744. */
  21745. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21746. for (var index = 0; index < this.lights.length; index++) {
  21747. if (this.lights[index].uniqueId === uniqueId) {
  21748. return this.lights[index];
  21749. }
  21750. }
  21751. return null;
  21752. };
  21753. /**
  21754. * get a particle system by id
  21755. * @param id {number} the particle system id
  21756. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21757. */
  21758. Scene.prototype.getParticleSystemByID = function (id) {
  21759. for (var index = 0; index < this.particleSystems.length; index++) {
  21760. if (this.particleSystems[index].id === id) {
  21761. return this.particleSystems[index];
  21762. }
  21763. }
  21764. return null;
  21765. };
  21766. /**
  21767. * get a geometry using its ID
  21768. * @param {string} the geometry's id
  21769. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21770. */
  21771. Scene.prototype.getGeometryByID = function (id) {
  21772. for (var index = 0; index < this._geometries.length; index++) {
  21773. if (this._geometries[index].id === id) {
  21774. return this._geometries[index];
  21775. }
  21776. }
  21777. return null;
  21778. };
  21779. /**
  21780. * add a new geometry to this scene.
  21781. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21782. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21783. * @return {boolean} was the geometry added or not
  21784. */
  21785. Scene.prototype.pushGeometry = function (geometry, force) {
  21786. if (!force && this.getGeometryByID(geometry.id)) {
  21787. return false;
  21788. }
  21789. this._geometries.push(geometry);
  21790. //notify the collision coordinator
  21791. if (this.collisionCoordinator) {
  21792. this.collisionCoordinator.onGeometryAdded(geometry);
  21793. }
  21794. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21795. return true;
  21796. };
  21797. /**
  21798. * Removes an existing geometry
  21799. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21800. * @return {boolean} was the geometry removed or not
  21801. */
  21802. Scene.prototype.removeGeometry = function (geometry) {
  21803. var index = this._geometries.indexOf(geometry);
  21804. if (index > -1) {
  21805. this._geometries.splice(index, 1);
  21806. //notify the collision coordinator
  21807. if (this.collisionCoordinator) {
  21808. this.collisionCoordinator.onGeometryDeleted(geometry);
  21809. }
  21810. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21811. return true;
  21812. }
  21813. return false;
  21814. };
  21815. Scene.prototype.getGeometries = function () {
  21816. return this._geometries;
  21817. };
  21818. /**
  21819. * Get the first added mesh found of a given ID
  21820. * @param {string} id - the id to search for
  21821. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21822. */
  21823. Scene.prototype.getMeshByID = function (id) {
  21824. for (var index = 0; index < this.meshes.length; index++) {
  21825. if (this.meshes[index].id === id) {
  21826. return this.meshes[index];
  21827. }
  21828. }
  21829. return null;
  21830. };
  21831. Scene.prototype.getMeshesByID = function (id) {
  21832. return this.meshes.filter(function (m) {
  21833. return m.id === id;
  21834. });
  21835. };
  21836. /**
  21837. * Get the first added transform node found of a given ID
  21838. * @param {string} id - the id to search for
  21839. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21840. */
  21841. Scene.prototype.getTransformNodeByID = function (id) {
  21842. for (var index = 0; index < this.transformNodes.length; index++) {
  21843. if (this.transformNodes[index].id === id) {
  21844. return this.transformNodes[index];
  21845. }
  21846. }
  21847. return null;
  21848. };
  21849. Scene.prototype.getTransformNodesByID = function (id) {
  21850. return this.transformNodes.filter(function (m) {
  21851. return m.id === id;
  21852. });
  21853. };
  21854. /**
  21855. * Get a mesh with its auto-generated unique id
  21856. * @param {number} uniqueId - the unique id to search for
  21857. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21858. */
  21859. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21860. for (var index = 0; index < this.meshes.length; index++) {
  21861. if (this.meshes[index].uniqueId === uniqueId) {
  21862. return this.meshes[index];
  21863. }
  21864. }
  21865. return null;
  21866. };
  21867. /**
  21868. * Get a the last added mesh found of a given ID
  21869. * @param {string} id - the id to search for
  21870. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21871. */
  21872. Scene.prototype.getLastMeshByID = function (id) {
  21873. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21874. if (this.meshes[index].id === id) {
  21875. return this.meshes[index];
  21876. }
  21877. }
  21878. return null;
  21879. };
  21880. /**
  21881. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21882. * @param {string} id - the id to search for
  21883. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21884. */
  21885. Scene.prototype.getLastEntryByID = function (id) {
  21886. var index;
  21887. for (index = this.meshes.length - 1; index >= 0; index--) {
  21888. if (this.meshes[index].id === id) {
  21889. return this.meshes[index];
  21890. }
  21891. }
  21892. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21893. if (this.transformNodes[index].id === id) {
  21894. return this.transformNodes[index];
  21895. }
  21896. }
  21897. for (index = this.cameras.length - 1; index >= 0; index--) {
  21898. if (this.cameras[index].id === id) {
  21899. return this.cameras[index];
  21900. }
  21901. }
  21902. for (index = this.lights.length - 1; index >= 0; index--) {
  21903. if (this.lights[index].id === id) {
  21904. return this.lights[index];
  21905. }
  21906. }
  21907. return null;
  21908. };
  21909. Scene.prototype.getNodeByID = function (id) {
  21910. var mesh = this.getMeshByID(id);
  21911. if (mesh) {
  21912. return mesh;
  21913. }
  21914. var light = this.getLightByID(id);
  21915. if (light) {
  21916. return light;
  21917. }
  21918. var camera = this.getCameraByID(id);
  21919. if (camera) {
  21920. return camera;
  21921. }
  21922. var bone = this.getBoneByID(id);
  21923. return bone;
  21924. };
  21925. Scene.prototype.getNodeByName = function (name) {
  21926. var mesh = this.getMeshByName(name);
  21927. if (mesh) {
  21928. return mesh;
  21929. }
  21930. var light = this.getLightByName(name);
  21931. if (light) {
  21932. return light;
  21933. }
  21934. var camera = this.getCameraByName(name);
  21935. if (camera) {
  21936. return camera;
  21937. }
  21938. var bone = this.getBoneByName(name);
  21939. return bone;
  21940. };
  21941. Scene.prototype.getMeshByName = function (name) {
  21942. for (var index = 0; index < this.meshes.length; index++) {
  21943. if (this.meshes[index].name === name) {
  21944. return this.meshes[index];
  21945. }
  21946. }
  21947. return null;
  21948. };
  21949. Scene.prototype.getTransformNodeByName = function (name) {
  21950. for (var index = 0; index < this.transformNodes.length; index++) {
  21951. if (this.transformNodes[index].name === name) {
  21952. return this.transformNodes[index];
  21953. }
  21954. }
  21955. return null;
  21956. };
  21957. Scene.prototype.getSoundByName = function (name) {
  21958. var index;
  21959. if (BABYLON.AudioEngine) {
  21960. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21961. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21962. return this.mainSoundTrack.soundCollection[index];
  21963. }
  21964. }
  21965. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21966. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21967. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21968. return this.soundTracks[sdIndex].soundCollection[index];
  21969. }
  21970. }
  21971. }
  21972. }
  21973. return null;
  21974. };
  21975. Scene.prototype.getLastSkeletonByID = function (id) {
  21976. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21977. if (this.skeletons[index].id === id) {
  21978. return this.skeletons[index];
  21979. }
  21980. }
  21981. return null;
  21982. };
  21983. Scene.prototype.getSkeletonById = function (id) {
  21984. for (var index = 0; index < this.skeletons.length; index++) {
  21985. if (this.skeletons[index].id === id) {
  21986. return this.skeletons[index];
  21987. }
  21988. }
  21989. return null;
  21990. };
  21991. Scene.prototype.getSkeletonByName = function (name) {
  21992. for (var index = 0; index < this.skeletons.length; index++) {
  21993. if (this.skeletons[index].name === name) {
  21994. return this.skeletons[index];
  21995. }
  21996. }
  21997. return null;
  21998. };
  21999. Scene.prototype.getMorphTargetManagerById = function (id) {
  22000. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22001. if (this.morphTargetManagers[index].uniqueId === id) {
  22002. return this.morphTargetManagers[index];
  22003. }
  22004. }
  22005. return null;
  22006. };
  22007. Scene.prototype.isActiveMesh = function (mesh) {
  22008. return (this._activeMeshes.indexOf(mesh) !== -1);
  22009. };
  22010. /**
  22011. * Return a the first highlight layer of the scene with a given name.
  22012. * @param name The name of the highlight layer to look for.
  22013. * @return The highlight layer if found otherwise null.
  22014. */
  22015. Scene.prototype.getHighlightLayerByName = function (name) {
  22016. for (var index = 0; index < this.highlightLayers.length; index++) {
  22017. if (this.highlightLayers[index].name === name) {
  22018. return this.highlightLayers[index];
  22019. }
  22020. }
  22021. return null;
  22022. };
  22023. Object.defineProperty(Scene.prototype, "uid", {
  22024. /**
  22025. * Return a unique id as a string which can serve as an identifier for the scene
  22026. */
  22027. get: function () {
  22028. if (!this._uid) {
  22029. this._uid = BABYLON.Tools.RandomId();
  22030. }
  22031. return this._uid;
  22032. },
  22033. enumerable: true,
  22034. configurable: true
  22035. });
  22036. /**
  22037. * Add an externaly attached data from its key.
  22038. * This method call will fail and return false, if such key already exists.
  22039. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22040. * @param key the unique key that identifies the data
  22041. * @param data the data object to associate to the key for this Engine instance
  22042. * @return true if no such key were already present and the data was added successfully, false otherwise
  22043. */
  22044. Scene.prototype.addExternalData = function (key, data) {
  22045. if (!this._externalData) {
  22046. this._externalData = new BABYLON.StringDictionary();
  22047. }
  22048. return this._externalData.add(key, data);
  22049. };
  22050. /**
  22051. * Get an externaly attached data from its key
  22052. * @param key the unique key that identifies the data
  22053. * @return the associated data, if present (can be null), or undefined if not present
  22054. */
  22055. Scene.prototype.getExternalData = function (key) {
  22056. if (!this._externalData) {
  22057. return null;
  22058. }
  22059. return this._externalData.get(key);
  22060. };
  22061. /**
  22062. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22063. * @param key the unique key that identifies the data
  22064. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22065. * @return the associated data, can be null if the factory returned null.
  22066. */
  22067. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22068. if (!this._externalData) {
  22069. this._externalData = new BABYLON.StringDictionary();
  22070. }
  22071. return this._externalData.getOrAddWithFactory(key, factory);
  22072. };
  22073. /**
  22074. * Remove an externaly attached data from the Engine instance
  22075. * @param key the unique key that identifies the data
  22076. * @return true if the data was successfully removed, false if it doesn't exist
  22077. */
  22078. Scene.prototype.removeExternalData = function (key) {
  22079. return this._externalData.remove(key);
  22080. };
  22081. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22082. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22083. if (mesh.showSubMeshesBoundingBox) {
  22084. var boundingInfo = subMesh.getBoundingInfo();
  22085. if (boundingInfo !== null && boundingInfo !== undefined) {
  22086. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22087. }
  22088. }
  22089. var material = subMesh.getMaterial();
  22090. if (material !== null && material !== undefined) {
  22091. // Render targets
  22092. if (material.getRenderTargetTextures !== undefined) {
  22093. if (this._processedMaterials.indexOf(material) === -1) {
  22094. this._processedMaterials.push(material);
  22095. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22096. }
  22097. }
  22098. // Dispatch
  22099. this._activeIndices.addCount(subMesh.indexCount, false);
  22100. this._renderingManager.dispatch(subMesh, mesh, material);
  22101. }
  22102. }
  22103. };
  22104. Scene.prototype._isInIntermediateRendering = function () {
  22105. return this._intermediateRendering;
  22106. };
  22107. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22108. this._activeMeshCandidateProvider = provider;
  22109. };
  22110. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22111. return this._activeMeshCandidateProvider;
  22112. };
  22113. /**
  22114. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22115. */
  22116. Scene.prototype.freezeActiveMeshes = function () {
  22117. this._evaluateActiveMeshes();
  22118. this._activeMeshesFrozen = true;
  22119. return this;
  22120. };
  22121. /**
  22122. * Use this function to restart evaluating active meshes on every frame
  22123. */
  22124. Scene.prototype.unfreezeActiveMeshes = function () {
  22125. this._activeMeshesFrozen = false;
  22126. return this;
  22127. };
  22128. Scene.prototype._evaluateActiveMeshes = function () {
  22129. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22130. return;
  22131. }
  22132. if (!this.activeCamera) {
  22133. return;
  22134. }
  22135. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22136. this.activeCamera._activeMeshes.reset();
  22137. this._activeMeshes.reset();
  22138. this._renderingManager.reset();
  22139. this._processedMaterials.reset();
  22140. this._activeParticleSystems.reset();
  22141. this._activeSkeletons.reset();
  22142. this._softwareSkinnedMeshes.reset();
  22143. if (this._boundingBoxRenderer) {
  22144. this._boundingBoxRenderer.reset();
  22145. }
  22146. // Meshes
  22147. var meshes;
  22148. var len;
  22149. var checkIsEnabled = true;
  22150. // Determine mesh candidates
  22151. if (this._activeMeshCandidateProvider !== undefined) {
  22152. // Use _activeMeshCandidateProvider
  22153. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22154. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22155. if (meshes !== undefined) {
  22156. len = meshes.length;
  22157. }
  22158. else {
  22159. len = 0;
  22160. }
  22161. }
  22162. else if (this._selectionOctree !== undefined) {
  22163. // Octree
  22164. var selection = this._selectionOctree.select(this._frustumPlanes);
  22165. meshes = selection.data;
  22166. len = selection.length;
  22167. }
  22168. else {
  22169. // Full scene traversal
  22170. len = this.meshes.length;
  22171. meshes = this.meshes;
  22172. }
  22173. // Check each mesh
  22174. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22175. mesh = meshes[meshIndex];
  22176. if (mesh.isBlocked) {
  22177. continue;
  22178. }
  22179. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22180. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22181. continue;
  22182. }
  22183. mesh.computeWorldMatrix();
  22184. // Intersections
  22185. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22186. this._meshesForIntersections.pushNoDuplicate(mesh);
  22187. }
  22188. // Switch to current LOD
  22189. meshLOD = mesh.getLOD(this.activeCamera);
  22190. if (meshLOD === undefined || meshLOD === null) {
  22191. continue;
  22192. }
  22193. mesh._preActivate();
  22194. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22195. this._activeMeshes.push(mesh);
  22196. this.activeCamera._activeMeshes.push(mesh);
  22197. mesh._activate(this._renderId);
  22198. if (meshLOD !== mesh) {
  22199. meshLOD._activate(this._renderId);
  22200. }
  22201. this._activeMesh(mesh, meshLOD);
  22202. }
  22203. }
  22204. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22205. // Particle systems
  22206. if (this.particlesEnabled) {
  22207. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22208. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22209. var particleSystem = this.particleSystems[particleIndex];
  22210. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22211. continue;
  22212. }
  22213. var emitter = particleSystem.emitter;
  22214. if (!emitter.position || emitter.isEnabled()) {
  22215. this._activeParticleSystems.push(particleSystem);
  22216. particleSystem.animate();
  22217. this._renderingManager.dispatchParticles(particleSystem);
  22218. }
  22219. }
  22220. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22221. }
  22222. };
  22223. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22224. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22225. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22226. mesh.skeleton.prepare();
  22227. }
  22228. if (!mesh.computeBonesUsingShaders) {
  22229. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22230. }
  22231. }
  22232. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22233. var boundingInfo = sourceMesh.getBoundingInfo();
  22234. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22235. }
  22236. if (mesh !== undefined && mesh !== null
  22237. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22238. // Submeshes Octrees
  22239. var len;
  22240. var subMeshes;
  22241. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22242. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22243. len = intersections.length;
  22244. subMeshes = intersections.data;
  22245. }
  22246. else {
  22247. subMeshes = mesh.subMeshes;
  22248. len = subMeshes.length;
  22249. }
  22250. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22251. subMesh = subMeshes[subIndex];
  22252. this._evaluateSubMesh(subMesh, mesh);
  22253. }
  22254. }
  22255. };
  22256. Scene.prototype.updateTransformMatrix = function (force) {
  22257. if (!this.activeCamera) {
  22258. return;
  22259. }
  22260. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22261. };
  22262. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22263. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22264. };
  22265. Scene.prototype._renderForCamera = function (camera) {
  22266. if (camera && camera._skipRendering) {
  22267. return;
  22268. }
  22269. var engine = this._engine;
  22270. this.activeCamera = camera;
  22271. if (!this.activeCamera)
  22272. throw new Error("Active camera not set");
  22273. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22274. // Viewport
  22275. engine.setViewport(this.activeCamera.viewport);
  22276. // Camera
  22277. this.resetCachedMaterial();
  22278. this._renderId++;
  22279. this.activeCamera.update();
  22280. this.updateTransformMatrix();
  22281. if (camera._alternateCamera) {
  22282. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22283. this._alternateRendering = true;
  22284. }
  22285. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22286. // Meshes
  22287. this._evaluateActiveMeshes();
  22288. // Software skinning
  22289. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22290. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22291. mesh.applySkeleton(mesh.skeleton);
  22292. }
  22293. // Render targets
  22294. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22295. var needsRestoreFrameBuffer = false;
  22296. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22297. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22298. }
  22299. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22300. this._intermediateRendering = true;
  22301. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22302. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22303. var renderTarget = this._renderTargets.data[renderIndex];
  22304. if (renderTarget._shouldRender()) {
  22305. this._renderId++;
  22306. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22307. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22308. }
  22309. }
  22310. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22311. this._intermediateRendering = false;
  22312. this._renderId++;
  22313. needsRestoreFrameBuffer = true; // Restore back buffer
  22314. }
  22315. // Render HighlightLayer Texture
  22316. var stencilState = this._engine.getStencilBuffer();
  22317. var renderhighlights = false;
  22318. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22319. this._intermediateRendering = true;
  22320. for (var i = 0; i < this.highlightLayers.length; i++) {
  22321. var highlightLayer = this.highlightLayers[i];
  22322. if (highlightLayer.shouldRender() &&
  22323. (!highlightLayer.camera ||
  22324. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22325. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22326. renderhighlights = true;
  22327. var renderTarget = highlightLayer._mainTexture;
  22328. if (renderTarget._shouldRender()) {
  22329. this._renderId++;
  22330. renderTarget.render(false, false);
  22331. needsRestoreFrameBuffer = true;
  22332. }
  22333. }
  22334. }
  22335. this._intermediateRendering = false;
  22336. this._renderId++;
  22337. }
  22338. if (needsRestoreFrameBuffer) {
  22339. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22340. }
  22341. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22342. // Prepare Frame
  22343. this.postProcessManager._prepareFrame();
  22344. // Backgrounds
  22345. var layerIndex;
  22346. var layer;
  22347. if (this.layers.length) {
  22348. engine.setDepthBuffer(false);
  22349. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22350. layer = this.layers[layerIndex];
  22351. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22352. layer.render();
  22353. }
  22354. }
  22355. engine.setDepthBuffer(true);
  22356. }
  22357. // Activate HighlightLayer stencil
  22358. if (renderhighlights) {
  22359. this._engine.setStencilBuffer(true);
  22360. }
  22361. // Render
  22362. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22363. this._renderingManager.render(null, null, true, true);
  22364. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22365. // Restore HighlightLayer stencil
  22366. if (renderhighlights) {
  22367. this._engine.setStencilBuffer(stencilState);
  22368. }
  22369. // Bounding boxes
  22370. if (this._boundingBoxRenderer) {
  22371. this._boundingBoxRenderer.render();
  22372. }
  22373. // Lens flares
  22374. if (this.lensFlaresEnabled) {
  22375. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22376. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22377. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22378. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22379. lensFlareSystem.render();
  22380. }
  22381. }
  22382. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22383. }
  22384. // Foregrounds
  22385. if (this.layers.length) {
  22386. engine.setDepthBuffer(false);
  22387. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22388. layer = this.layers[layerIndex];
  22389. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22390. layer.render();
  22391. }
  22392. }
  22393. engine.setDepthBuffer(true);
  22394. }
  22395. // Highlight Layer
  22396. if (renderhighlights) {
  22397. engine.setDepthBuffer(false);
  22398. for (var i = 0; i < this.highlightLayers.length; i++) {
  22399. if (this.highlightLayers[i].shouldRender()) {
  22400. this.highlightLayers[i].render();
  22401. }
  22402. }
  22403. engine.setDepthBuffer(true);
  22404. }
  22405. // Finalize frame
  22406. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22407. // Reset some special arrays
  22408. this._renderTargets.reset();
  22409. this._alternateRendering = false;
  22410. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22411. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22412. };
  22413. Scene.prototype._processSubCameras = function (camera) {
  22414. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22415. this._renderForCamera(camera);
  22416. return;
  22417. }
  22418. // Update camera
  22419. if (this.activeCamera) {
  22420. this.activeCamera.update();
  22421. }
  22422. // rig cameras
  22423. for (var index = 0; index < camera._rigCameras.length; index++) {
  22424. this._renderForCamera(camera._rigCameras[index]);
  22425. }
  22426. this.activeCamera = camera;
  22427. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22428. };
  22429. Scene.prototype._checkIntersections = function () {
  22430. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22431. var sourceMesh = this._meshesForIntersections.data[index];
  22432. if (!sourceMesh.actionManager) {
  22433. continue;
  22434. }
  22435. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22436. var action = sourceMesh.actionManager.actions[actionIndex];
  22437. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22438. var parameters = action.getTriggerParameter();
  22439. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22440. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22441. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22442. if (areIntersecting && currentIntersectionInProgress === -1) {
  22443. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22444. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22445. sourceMesh._intersectionsInProgress.push(otherMesh);
  22446. }
  22447. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22448. sourceMesh._intersectionsInProgress.push(otherMesh);
  22449. }
  22450. }
  22451. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22452. //They intersected, and now they don't.
  22453. //is this trigger an exit trigger? execute an event.
  22454. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22455. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22456. }
  22457. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22458. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22459. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22460. }
  22461. }
  22462. }
  22463. }
  22464. }
  22465. };
  22466. Scene.prototype.render = function () {
  22467. if (this.isDisposed) {
  22468. return;
  22469. }
  22470. this._activeParticles.fetchNewFrame();
  22471. this._totalVertices.fetchNewFrame();
  22472. this._activeIndices.fetchNewFrame();
  22473. this._activeBones.fetchNewFrame();
  22474. this._meshesForIntersections.reset();
  22475. this.resetCachedMaterial();
  22476. this.onBeforeAnimationsObservable.notifyObservers(this);
  22477. // Actions
  22478. if (this.actionManager) {
  22479. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22480. }
  22481. //Simplification Queue
  22482. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22483. this.simplificationQueue.executeNext();
  22484. }
  22485. if (this._engine.isDeterministicLockStep()) {
  22486. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22487. var defaultFPS = (60.0 / 1000.0);
  22488. var defaultFrameTime = 1000 / 60; // frame time in MS
  22489. if (this._physicsEngine) {
  22490. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22491. }
  22492. var stepsTaken = 0;
  22493. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22494. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22495. internalSteps = Math.min(internalSteps, maxSubSteps);
  22496. do {
  22497. this.onBeforeStepObservable.notifyObservers(this);
  22498. // Animations
  22499. this._animationRatio = defaultFrameTime * defaultFPS;
  22500. this._animate();
  22501. this.onAfterAnimationsObservable.notifyObservers(this);
  22502. // Physics
  22503. if (this._physicsEngine) {
  22504. this.onBeforePhysicsObservable.notifyObservers(this);
  22505. this._physicsEngine._step(defaultFrameTime / 1000);
  22506. this.onAfterPhysicsObservable.notifyObservers(this);
  22507. }
  22508. this.onAfterStepObservable.notifyObservers(this);
  22509. this._currentStepId++;
  22510. stepsTaken++;
  22511. deltaTime -= defaultFrameTime;
  22512. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22513. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22514. }
  22515. else {
  22516. // Animations
  22517. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22518. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22519. this._animate();
  22520. this.onAfterAnimationsObservable.notifyObservers(this);
  22521. // Physics
  22522. if (this._physicsEngine) {
  22523. this.onBeforePhysicsObservable.notifyObservers(this);
  22524. this._physicsEngine._step(deltaTime / 1000.0);
  22525. this.onAfterPhysicsObservable.notifyObservers(this);
  22526. }
  22527. }
  22528. // update gamepad manager
  22529. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22530. this._gamepadManager._checkGamepadsStatus();
  22531. }
  22532. // Before render
  22533. this.onBeforeRenderObservable.notifyObservers(this);
  22534. // Customs render targets
  22535. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22536. var engine = this.getEngine();
  22537. var currentActiveCamera = this.activeCamera;
  22538. if (this.renderTargetsEnabled) {
  22539. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22540. this._intermediateRendering = true;
  22541. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22542. var renderTarget = this.customRenderTargets[customIndex];
  22543. if (renderTarget._shouldRender()) {
  22544. this._renderId++;
  22545. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22546. if (!this.activeCamera)
  22547. throw new Error("Active camera not set");
  22548. // Viewport
  22549. engine.setViewport(this.activeCamera.viewport);
  22550. // Camera
  22551. this.updateTransformMatrix();
  22552. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22553. }
  22554. }
  22555. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22556. this._intermediateRendering = false;
  22557. this._renderId++;
  22558. }
  22559. // Restore back buffer
  22560. if (this.customRenderTargets.length > 0) {
  22561. engine.restoreDefaultFramebuffer();
  22562. }
  22563. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22564. this.activeCamera = currentActiveCamera;
  22565. // Procedural textures
  22566. if (this.proceduralTexturesEnabled) {
  22567. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22568. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22569. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22570. if (proceduralTexture._shouldRender()) {
  22571. proceduralTexture.render();
  22572. }
  22573. }
  22574. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22575. }
  22576. // Clear
  22577. if (this.autoClearDepthAndStencil || this.autoClear) {
  22578. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22579. }
  22580. // Shadows
  22581. if (this.shadowsEnabled) {
  22582. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22583. var light = this.lights[lightIndex];
  22584. var shadowGenerator = light.getShadowGenerator();
  22585. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22586. var shadowMap = (shadowGenerator.getShadowMap());
  22587. if (this.textures.indexOf(shadowMap) !== -1) {
  22588. this._renderTargets.push(shadowMap);
  22589. }
  22590. }
  22591. }
  22592. }
  22593. // Depth renderer
  22594. if (this._depthRenderer) {
  22595. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22596. }
  22597. // Geometry renderer
  22598. if (this._geometryBufferRenderer) {
  22599. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22600. }
  22601. // RenderPipeline
  22602. if (this._postProcessRenderPipelineManager) {
  22603. this._postProcessRenderPipelineManager.update();
  22604. }
  22605. // Multi-cameras?
  22606. if (this.activeCameras.length > 0) {
  22607. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22608. if (cameraIndex > 0) {
  22609. this._engine.clear(null, false, true, true);
  22610. }
  22611. this._processSubCameras(this.activeCameras[cameraIndex]);
  22612. }
  22613. }
  22614. else {
  22615. if (!this.activeCamera) {
  22616. throw new Error("No camera defined");
  22617. }
  22618. this._processSubCameras(this.activeCamera);
  22619. }
  22620. // Intersection checks
  22621. this._checkIntersections();
  22622. // Update the audio listener attached to the camera
  22623. if (BABYLON.AudioEngine) {
  22624. this._updateAudioParameters();
  22625. }
  22626. // After render
  22627. if (this.afterRender) {
  22628. this.afterRender();
  22629. }
  22630. this.onAfterRenderObservable.notifyObservers(this);
  22631. // Cleaning
  22632. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22633. var data = this._toBeDisposed.data[index];
  22634. if (data) {
  22635. data.dispose();
  22636. }
  22637. this._toBeDisposed[index] = null;
  22638. }
  22639. this._toBeDisposed.reset();
  22640. if (this.dumpNextRenderTargets) {
  22641. this.dumpNextRenderTargets = false;
  22642. }
  22643. this._activeBones.addCount(0, true);
  22644. this._activeIndices.addCount(0, true);
  22645. this._activeParticles.addCount(0, true);
  22646. };
  22647. Scene.prototype._updateAudioParameters = function () {
  22648. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22649. return;
  22650. }
  22651. var listeningCamera;
  22652. var audioEngine = BABYLON.Engine.audioEngine;
  22653. if (this.activeCameras.length > 0) {
  22654. listeningCamera = this.activeCameras[0];
  22655. }
  22656. else {
  22657. listeningCamera = this.activeCamera;
  22658. }
  22659. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22660. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22661. // for VR cameras
  22662. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22663. listeningCamera = listeningCamera.rigCameras[0];
  22664. }
  22665. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22666. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22667. cameraDirection.normalize();
  22668. // To avoid some errors on GearVR
  22669. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22670. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22671. }
  22672. var i;
  22673. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22674. var sound = this.mainSoundTrack.soundCollection[i];
  22675. if (sound.useCustomAttenuation) {
  22676. sound.updateDistanceFromListener();
  22677. }
  22678. }
  22679. for (i = 0; i < this.soundTracks.length; i++) {
  22680. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22681. sound = this.soundTracks[i].soundCollection[j];
  22682. if (sound.useCustomAttenuation) {
  22683. sound.updateDistanceFromListener();
  22684. }
  22685. }
  22686. }
  22687. }
  22688. };
  22689. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22690. // Audio
  22691. get: function () {
  22692. return this._audioEnabled;
  22693. },
  22694. set: function (value) {
  22695. this._audioEnabled = value;
  22696. if (BABYLON.AudioEngine) {
  22697. if (this._audioEnabled) {
  22698. this._enableAudio();
  22699. }
  22700. else {
  22701. this._disableAudio();
  22702. }
  22703. }
  22704. },
  22705. enumerable: true,
  22706. configurable: true
  22707. });
  22708. Scene.prototype._disableAudio = function () {
  22709. var i;
  22710. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22711. this.mainSoundTrack.soundCollection[i].pause();
  22712. }
  22713. for (i = 0; i < this.soundTracks.length; i++) {
  22714. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22715. this.soundTracks[i].soundCollection[j].pause();
  22716. }
  22717. }
  22718. };
  22719. Scene.prototype._enableAudio = function () {
  22720. var i;
  22721. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22722. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22723. this.mainSoundTrack.soundCollection[i].play();
  22724. }
  22725. }
  22726. for (i = 0; i < this.soundTracks.length; i++) {
  22727. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22728. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22729. this.soundTracks[i].soundCollection[j].play();
  22730. }
  22731. }
  22732. }
  22733. };
  22734. Object.defineProperty(Scene.prototype, "headphone", {
  22735. get: function () {
  22736. return this._headphone;
  22737. },
  22738. set: function (value) {
  22739. this._headphone = value;
  22740. if (BABYLON.AudioEngine) {
  22741. if (this._headphone) {
  22742. this._switchAudioModeForHeadphones();
  22743. }
  22744. else {
  22745. this._switchAudioModeForNormalSpeakers();
  22746. }
  22747. }
  22748. },
  22749. enumerable: true,
  22750. configurable: true
  22751. });
  22752. Scene.prototype._switchAudioModeForHeadphones = function () {
  22753. this.mainSoundTrack.switchPanningModelToHRTF();
  22754. for (var i = 0; i < this.soundTracks.length; i++) {
  22755. this.soundTracks[i].switchPanningModelToHRTF();
  22756. }
  22757. };
  22758. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22759. this.mainSoundTrack.switchPanningModelToEqualPower();
  22760. for (var i = 0; i < this.soundTracks.length; i++) {
  22761. this.soundTracks[i].switchPanningModelToEqualPower();
  22762. }
  22763. };
  22764. Scene.prototype.enableDepthRenderer = function () {
  22765. if (this._depthRenderer) {
  22766. return this._depthRenderer;
  22767. }
  22768. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22769. return this._depthRenderer;
  22770. };
  22771. Scene.prototype.disableDepthRenderer = function () {
  22772. if (!this._depthRenderer) {
  22773. return;
  22774. }
  22775. this._depthRenderer.dispose();
  22776. this._depthRenderer = null;
  22777. };
  22778. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22779. if (ratio === void 0) { ratio = 1; }
  22780. if (this._geometryBufferRenderer) {
  22781. return this._geometryBufferRenderer;
  22782. }
  22783. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22784. if (!this._geometryBufferRenderer.isSupported) {
  22785. this._geometryBufferRenderer = null;
  22786. }
  22787. return this._geometryBufferRenderer;
  22788. };
  22789. Scene.prototype.disableGeometryBufferRenderer = function () {
  22790. if (!this._geometryBufferRenderer) {
  22791. return;
  22792. }
  22793. this._geometryBufferRenderer.dispose();
  22794. this._geometryBufferRenderer = null;
  22795. };
  22796. Scene.prototype.freezeMaterials = function () {
  22797. for (var i = 0; i < this.materials.length; i++) {
  22798. this.materials[i].freeze();
  22799. }
  22800. };
  22801. Scene.prototype.unfreezeMaterials = function () {
  22802. for (var i = 0; i < this.materials.length; i++) {
  22803. this.materials[i].unfreeze();
  22804. }
  22805. };
  22806. Scene.prototype.dispose = function () {
  22807. this.beforeRender = null;
  22808. this.afterRender = null;
  22809. this.skeletons = [];
  22810. this.morphTargetManagers = [];
  22811. this.importedMeshesFiles = new Array();
  22812. this.stopAllAnimations();
  22813. this.resetCachedMaterial();
  22814. if (this._depthRenderer) {
  22815. this._depthRenderer.dispose();
  22816. }
  22817. if (this._gamepadManager) {
  22818. this._gamepadManager.dispose();
  22819. this._gamepadManager = null;
  22820. }
  22821. // Smart arrays
  22822. if (this.activeCamera) {
  22823. this.activeCamera._activeMeshes.dispose();
  22824. this.activeCamera = null;
  22825. }
  22826. this._activeMeshes.dispose();
  22827. this._renderingManager.dispose();
  22828. this._processedMaterials.dispose();
  22829. this._activeParticleSystems.dispose();
  22830. this._activeSkeletons.dispose();
  22831. this._softwareSkinnedMeshes.dispose();
  22832. this._renderTargets.dispose();
  22833. if (this._boundingBoxRenderer) {
  22834. this._boundingBoxRenderer.dispose();
  22835. }
  22836. this._meshesForIntersections.dispose();
  22837. this._toBeDisposed.dispose();
  22838. // Abort active requests
  22839. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22840. var request = _a[_i];
  22841. request.abort();
  22842. }
  22843. // Debug layer
  22844. if (this._debugLayer) {
  22845. this._debugLayer.hide();
  22846. }
  22847. // Events
  22848. this.onDisposeObservable.notifyObservers(this);
  22849. this.onDisposeObservable.clear();
  22850. this.onBeforeRenderObservable.clear();
  22851. this.onAfterRenderObservable.clear();
  22852. this.OnBeforeRenderTargetsRenderObservable.clear();
  22853. this.OnAfterRenderTargetsRenderObservable.clear();
  22854. this.onAfterStepObservable.clear();
  22855. this.onBeforeStepObservable.clear();
  22856. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22857. this.onAfterActiveMeshesEvaluationObservable.clear();
  22858. this.onBeforeParticlesRenderingObservable.clear();
  22859. this.onAfterParticlesRenderingObservable.clear();
  22860. this.onBeforeSpritesRenderingObservable.clear();
  22861. this.onAfterSpritesRenderingObservable.clear();
  22862. this.onBeforeDrawPhaseObservable.clear();
  22863. this.onAfterDrawPhaseObservable.clear();
  22864. this.onBeforePhysicsObservable.clear();
  22865. this.onAfterPhysicsObservable.clear();
  22866. this.onBeforeAnimationsObservable.clear();
  22867. this.onAfterAnimationsObservable.clear();
  22868. this.onDataLoadedObservable.clear();
  22869. this.detachControl();
  22870. // Release sounds & sounds tracks
  22871. if (BABYLON.AudioEngine) {
  22872. this.disposeSounds();
  22873. }
  22874. // VR Helper
  22875. if (this.VRHelper) {
  22876. this.VRHelper.dispose();
  22877. }
  22878. // Detach cameras
  22879. var canvas = this._engine.getRenderingCanvas();
  22880. if (canvas) {
  22881. var index;
  22882. for (index = 0; index < this.cameras.length; index++) {
  22883. this.cameras[index].detachControl(canvas);
  22884. }
  22885. }
  22886. // Release animation groups
  22887. while (this.animationGroups.length) {
  22888. this.animationGroups[0].dispose();
  22889. }
  22890. // Release lights
  22891. while (this.lights.length) {
  22892. this.lights[0].dispose();
  22893. }
  22894. // Release meshes
  22895. while (this.meshes.length) {
  22896. this.meshes[0].dispose(true);
  22897. }
  22898. while (this.transformNodes.length) {
  22899. this.removeTransformNode(this.transformNodes[0]);
  22900. }
  22901. // Release cameras
  22902. while (this.cameras.length) {
  22903. this.cameras[0].dispose();
  22904. }
  22905. // Release materials
  22906. if (this.defaultMaterial) {
  22907. this.defaultMaterial.dispose();
  22908. }
  22909. while (this.multiMaterials.length) {
  22910. this.multiMaterials[0].dispose();
  22911. }
  22912. while (this.materials.length) {
  22913. this.materials[0].dispose();
  22914. }
  22915. // Release particles
  22916. while (this.particleSystems.length) {
  22917. this.particleSystems[0].dispose();
  22918. }
  22919. // Release sprites
  22920. while (this.spriteManagers.length) {
  22921. this.spriteManagers[0].dispose();
  22922. }
  22923. // Release postProcesses
  22924. while (this.postProcesses.length) {
  22925. this.postProcesses[0].dispose();
  22926. }
  22927. // Release layers
  22928. while (this.layers.length) {
  22929. this.layers[0].dispose();
  22930. }
  22931. while (this.highlightLayers.length) {
  22932. this.highlightLayers[0].dispose();
  22933. }
  22934. // Release textures
  22935. while (this.textures.length) {
  22936. this.textures[0].dispose();
  22937. }
  22938. // Release UBO
  22939. this._sceneUbo.dispose();
  22940. if (this._alternateSceneUbo) {
  22941. this._alternateSceneUbo.dispose();
  22942. }
  22943. // Post-processes
  22944. this.postProcessManager.dispose();
  22945. if (this._postProcessRenderPipelineManager) {
  22946. this._postProcessRenderPipelineManager.dispose();
  22947. }
  22948. // Physics
  22949. if (this._physicsEngine) {
  22950. this.disablePhysicsEngine();
  22951. }
  22952. // Remove from engine
  22953. index = this._engine.scenes.indexOf(this);
  22954. if (index > -1) {
  22955. this._engine.scenes.splice(index, 1);
  22956. }
  22957. this._engine.wipeCaches(true);
  22958. this._isDisposed = true;
  22959. };
  22960. Object.defineProperty(Scene.prototype, "isDisposed", {
  22961. get: function () {
  22962. return this._isDisposed;
  22963. },
  22964. enumerable: true,
  22965. configurable: true
  22966. });
  22967. // Release sounds & sounds tracks
  22968. Scene.prototype.disposeSounds = function () {
  22969. if (!this._mainSoundTrack) {
  22970. return;
  22971. }
  22972. this.mainSoundTrack.dispose();
  22973. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22974. this.soundTracks[scIndex].dispose();
  22975. }
  22976. };
  22977. // Octrees
  22978. Scene.prototype.getWorldExtends = function () {
  22979. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22980. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22981. for (var index = 0; index < this.meshes.length; index++) {
  22982. var mesh = this.meshes[index];
  22983. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22984. continue;
  22985. }
  22986. mesh.computeWorldMatrix(true);
  22987. var boundingInfo = mesh.getBoundingInfo();
  22988. var minBox = boundingInfo.boundingBox.minimumWorld;
  22989. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22990. BABYLON.Tools.CheckExtends(minBox, min, max);
  22991. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22992. }
  22993. return {
  22994. min: min,
  22995. max: max
  22996. };
  22997. };
  22998. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22999. if (maxCapacity === void 0) { maxCapacity = 64; }
  23000. if (maxDepth === void 0) { maxDepth = 2; }
  23001. if (!this._selectionOctree) {
  23002. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23003. }
  23004. var worldExtends = this.getWorldExtends();
  23005. // Update octree
  23006. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23007. return this._selectionOctree;
  23008. };
  23009. // Picking
  23010. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23011. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23012. var result = BABYLON.Ray.Zero();
  23013. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23014. return result;
  23015. };
  23016. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23017. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23018. var engine = this._engine;
  23019. if (!camera) {
  23020. if (!this.activeCamera)
  23021. throw new Error("Active camera not set");
  23022. camera = this.activeCamera;
  23023. }
  23024. var cameraViewport = camera.viewport;
  23025. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23026. // Moving coordinates to local viewport world
  23027. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23028. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23029. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23030. return this;
  23031. };
  23032. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23033. var result = BABYLON.Ray.Zero();
  23034. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23035. return result;
  23036. };
  23037. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23038. if (!BABYLON.PickingInfo) {
  23039. return this;
  23040. }
  23041. var engine = this._engine;
  23042. if (!camera) {
  23043. if (!this.activeCamera)
  23044. throw new Error("Active camera not set");
  23045. camera = this.activeCamera;
  23046. }
  23047. var cameraViewport = camera.viewport;
  23048. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23049. var identity = BABYLON.Matrix.Identity();
  23050. // Moving coordinates to local viewport world
  23051. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23052. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23053. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23054. return this;
  23055. };
  23056. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23057. if (!BABYLON.PickingInfo) {
  23058. return null;
  23059. }
  23060. var pickingInfo = null;
  23061. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23062. var mesh = this.meshes[meshIndex];
  23063. if (predicate) {
  23064. if (!predicate(mesh)) {
  23065. continue;
  23066. }
  23067. }
  23068. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23069. continue;
  23070. }
  23071. var world = mesh.getWorldMatrix();
  23072. var ray = rayFunction(world);
  23073. var result = mesh.intersects(ray, fastCheck);
  23074. if (!result || !result.hit)
  23075. continue;
  23076. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23077. continue;
  23078. pickingInfo = result;
  23079. if (fastCheck) {
  23080. break;
  23081. }
  23082. }
  23083. return pickingInfo || new BABYLON.PickingInfo();
  23084. };
  23085. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23086. if (!BABYLON.PickingInfo) {
  23087. return null;
  23088. }
  23089. var pickingInfos = new Array();
  23090. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23091. var mesh = this.meshes[meshIndex];
  23092. if (predicate) {
  23093. if (!predicate(mesh)) {
  23094. continue;
  23095. }
  23096. }
  23097. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23098. continue;
  23099. }
  23100. var world = mesh.getWorldMatrix();
  23101. var ray = rayFunction(world);
  23102. var result = mesh.intersects(ray, false);
  23103. if (!result || !result.hit)
  23104. continue;
  23105. pickingInfos.push(result);
  23106. }
  23107. return pickingInfos;
  23108. };
  23109. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23110. if (!BABYLON.PickingInfo) {
  23111. return null;
  23112. }
  23113. var pickingInfo = null;
  23114. if (!camera) {
  23115. if (!this.activeCamera) {
  23116. return null;
  23117. }
  23118. camera = this.activeCamera;
  23119. }
  23120. if (this.spriteManagers.length > 0) {
  23121. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23122. var spriteManager = this.spriteManagers[spriteIndex];
  23123. if (!spriteManager.isPickable) {
  23124. continue;
  23125. }
  23126. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23127. if (!result || !result.hit)
  23128. continue;
  23129. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23130. continue;
  23131. pickingInfo = result;
  23132. if (fastCheck) {
  23133. break;
  23134. }
  23135. }
  23136. }
  23137. return pickingInfo || new BABYLON.PickingInfo();
  23138. };
  23139. /** Launch a ray to try to pick a mesh in the scene
  23140. * @param x position on screen
  23141. * @param y position on screen
  23142. * @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
  23143. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23144. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23145. */
  23146. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23147. var _this = this;
  23148. if (!BABYLON.PickingInfo) {
  23149. return null;
  23150. }
  23151. return this._internalPick(function (world) {
  23152. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23153. return _this._tempPickingRay;
  23154. }, predicate, fastCheck);
  23155. };
  23156. /** Launch a ray to try to pick a sprite in the scene
  23157. * @param x position on screen
  23158. * @param y position on screen
  23159. * @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
  23160. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23161. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23162. */
  23163. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23164. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23165. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23166. };
  23167. /** Use the given ray to pick a mesh in the scene
  23168. * @param ray The ray to use to pick meshes
  23169. * @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
  23170. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23171. */
  23172. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23173. var _this = this;
  23174. return this._internalPick(function (world) {
  23175. if (!_this._pickWithRayInverseMatrix) {
  23176. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23177. }
  23178. world.invertToRef(_this._pickWithRayInverseMatrix);
  23179. if (!_this._cachedRayForTransform) {
  23180. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23181. }
  23182. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23183. return _this._cachedRayForTransform;
  23184. }, predicate, fastCheck);
  23185. };
  23186. /**
  23187. * Launch a ray to try to pick a mesh in the scene
  23188. * @param x X position on screen
  23189. * @param y Y position on screen
  23190. * @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
  23191. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23192. */
  23193. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23194. var _this = this;
  23195. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23196. };
  23197. /**
  23198. * Launch a ray to try to pick a mesh in the scene
  23199. * @param ray Ray to use
  23200. * @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
  23201. */
  23202. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23203. var _this = this;
  23204. return this._internalMultiPick(function (world) {
  23205. if (!_this._pickWithRayInverseMatrix) {
  23206. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23207. }
  23208. world.invertToRef(_this._pickWithRayInverseMatrix);
  23209. if (!_this._cachedRayForTransform) {
  23210. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23211. }
  23212. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23213. return _this._cachedRayForTransform;
  23214. }, predicate);
  23215. };
  23216. Scene.prototype.setPointerOverMesh = function (mesh) {
  23217. if (this._pointerOverMesh === mesh) {
  23218. return;
  23219. }
  23220. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23221. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23222. }
  23223. this._pointerOverMesh = mesh;
  23224. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23225. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23226. }
  23227. };
  23228. Scene.prototype.getPointerOverMesh = function () {
  23229. return this._pointerOverMesh;
  23230. };
  23231. Scene.prototype.setPointerOverSprite = function (sprite) {
  23232. if (this._pointerOverSprite === sprite) {
  23233. return;
  23234. }
  23235. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23236. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23237. }
  23238. this._pointerOverSprite = sprite;
  23239. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23240. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23241. }
  23242. };
  23243. Scene.prototype.getPointerOverSprite = function () {
  23244. return this._pointerOverSprite;
  23245. };
  23246. // Physics
  23247. Scene.prototype.getPhysicsEngine = function () {
  23248. return this._physicsEngine;
  23249. };
  23250. /**
  23251. * Enables physics to the current scene
  23252. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23253. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23254. * @return {boolean} was the physics engine initialized
  23255. */
  23256. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23257. if (gravity === void 0) { gravity = null; }
  23258. if (this._physicsEngine) {
  23259. return true;
  23260. }
  23261. try {
  23262. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23263. return true;
  23264. }
  23265. catch (e) {
  23266. BABYLON.Tools.Error(e.message);
  23267. return false;
  23268. }
  23269. };
  23270. Scene.prototype.disablePhysicsEngine = function () {
  23271. if (!this._physicsEngine) {
  23272. return;
  23273. }
  23274. this._physicsEngine.dispose();
  23275. this._physicsEngine = null;
  23276. };
  23277. Scene.prototype.isPhysicsEnabled = function () {
  23278. return this._physicsEngine !== undefined;
  23279. };
  23280. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23281. var mesh = compound.parts[0].mesh;
  23282. if (mesh.physicsImpostor) {
  23283. mesh.physicsImpostor.dispose();
  23284. mesh.physicsImpostor = null;
  23285. }
  23286. };
  23287. // Misc.
  23288. Scene.prototype._rebuildGeometries = function () {
  23289. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23290. var geometry = _a[_i];
  23291. geometry._rebuild();
  23292. }
  23293. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23294. var mesh = _c[_b];
  23295. mesh._rebuild();
  23296. }
  23297. if (this.postProcessManager) {
  23298. this.postProcessManager._rebuild();
  23299. }
  23300. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23301. var layer = _e[_d];
  23302. layer._rebuild();
  23303. }
  23304. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23305. var highlightLayer = _g[_f];
  23306. highlightLayer._rebuild();
  23307. }
  23308. if (this._boundingBoxRenderer) {
  23309. this._boundingBoxRenderer._rebuild();
  23310. }
  23311. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23312. var system = _j[_h];
  23313. system.rebuild();
  23314. }
  23315. if (this._postProcessRenderPipelineManager) {
  23316. this._postProcessRenderPipelineManager._rebuild();
  23317. }
  23318. };
  23319. Scene.prototype._rebuildTextures = function () {
  23320. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23321. var texture = _a[_i];
  23322. texture._rebuild();
  23323. }
  23324. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23325. };
  23326. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23327. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23328. if (replace === void 0) { replace = false; }
  23329. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23330. // Dispose existing camera or light in replace mode.
  23331. if (replace) {
  23332. if (this.activeCamera) {
  23333. this.activeCamera.dispose();
  23334. this.activeCamera = null;
  23335. }
  23336. if (this.lights) {
  23337. for (var i = 0; i < this.lights.length; i++) {
  23338. this.lights[i].dispose();
  23339. }
  23340. }
  23341. }
  23342. // Light
  23343. if (this.lights.length === 0) {
  23344. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23345. }
  23346. // Camera
  23347. if (!this.activeCamera) {
  23348. var worldExtends = this.getWorldExtends();
  23349. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23350. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23351. var camera;
  23352. var radius = worldSize.length() * 1.5;
  23353. if (createArcRotateCamera) {
  23354. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23355. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23356. arcRotateCamera.wheelPrecision = 100 / radius;
  23357. camera = arcRotateCamera;
  23358. }
  23359. else {
  23360. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23361. freeCamera.setTarget(worldCenter);
  23362. camera = freeCamera;
  23363. }
  23364. camera.minZ = radius * 0.01;
  23365. camera.maxZ = radius * 1000;
  23366. camera.speed = radius * 0.2;
  23367. this.activeCamera = camera;
  23368. var canvas = this.getEngine().getRenderingCanvas();
  23369. if (attachCameraControls && canvas) {
  23370. camera.attachControl(canvas);
  23371. }
  23372. }
  23373. };
  23374. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23375. if (pbr === void 0) { pbr = false; }
  23376. if (scale === void 0) { scale = 1000; }
  23377. if (blur === void 0) { blur = 0; }
  23378. if (environmentTexture) {
  23379. this.environmentTexture = environmentTexture;
  23380. }
  23381. if (!this.environmentTexture) {
  23382. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23383. return null;
  23384. }
  23385. // Skybox
  23386. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23387. if (pbr) {
  23388. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23389. hdrSkyboxMaterial.backFaceCulling = false;
  23390. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23391. if (hdrSkyboxMaterial.reflectionTexture) {
  23392. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23393. }
  23394. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23395. hdrSkyboxMaterial.disableLighting = true;
  23396. hdrSkyboxMaterial.twoSidedLighting = true;
  23397. hdrSkybox.infiniteDistance = true;
  23398. hdrSkybox.material = hdrSkyboxMaterial;
  23399. }
  23400. else {
  23401. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23402. skyboxMaterial.backFaceCulling = false;
  23403. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23404. if (skyboxMaterial.reflectionTexture) {
  23405. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23406. }
  23407. skyboxMaterial.disableLighting = true;
  23408. hdrSkybox.infiniteDistance = true;
  23409. hdrSkybox.material = skyboxMaterial;
  23410. }
  23411. return hdrSkybox;
  23412. };
  23413. Scene.prototype.createDefaultEnvironment = function (options) {
  23414. if (BABYLON.EnvironmentHelper) {
  23415. return new BABYLON.EnvironmentHelper(options, this);
  23416. }
  23417. return null;
  23418. };
  23419. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23420. if (webVROptions === void 0) { webVROptions = {}; }
  23421. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23422. };
  23423. // Tags
  23424. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23425. if (tagsQuery === undefined) {
  23426. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23427. return list;
  23428. }
  23429. var listByTags = [];
  23430. forEach = forEach || (function (item) { return; });
  23431. for (var i in list) {
  23432. var item = list[i];
  23433. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23434. listByTags.push(item);
  23435. forEach(item);
  23436. }
  23437. }
  23438. return listByTags;
  23439. };
  23440. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23441. return this._getByTags(this.meshes, tagsQuery, forEach);
  23442. };
  23443. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23444. return this._getByTags(this.cameras, tagsQuery, forEach);
  23445. };
  23446. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23447. return this._getByTags(this.lights, tagsQuery, forEach);
  23448. };
  23449. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23450. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23451. };
  23452. /**
  23453. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23454. * This allowed control for front to back rendering or reversly depending of the special needs.
  23455. *
  23456. * @param renderingGroupId The rendering group id corresponding to its index
  23457. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23458. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23459. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23460. */
  23461. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23462. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23463. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23464. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23465. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23466. };
  23467. /**
  23468. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23469. *
  23470. * @param renderingGroupId The rendering group id corresponding to its index
  23471. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23472. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23473. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23474. */
  23475. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23476. if (depth === void 0) { depth = true; }
  23477. if (stencil === void 0) { stencil = true; }
  23478. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23479. };
  23480. /**
  23481. * Will flag all materials as dirty to trigger new shader compilation
  23482. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23483. */
  23484. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23485. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23486. var material = _a[_i];
  23487. if (predicate && !predicate(material)) {
  23488. continue;
  23489. }
  23490. material.markAsDirty(flag);
  23491. }
  23492. };
  23493. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23494. var _this = this;
  23495. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23496. this._activeRequests.push(request);
  23497. request.onCompleteObservable.add(function (request) {
  23498. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23499. });
  23500. return request;
  23501. };
  23502. /** @ignore */
  23503. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23504. var _this = this;
  23505. return new Promise(function (resolve, reject) {
  23506. _this._loadFile(url, function (data) {
  23507. resolve(data);
  23508. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23509. reject(exception);
  23510. });
  23511. });
  23512. };
  23513. // Statics
  23514. Scene._FOGMODE_NONE = 0;
  23515. Scene._FOGMODE_EXP = 1;
  23516. Scene._FOGMODE_EXP2 = 2;
  23517. Scene._FOGMODE_LINEAR = 3;
  23518. Scene._uniqueIdCounter = 0;
  23519. Scene.MinDeltaTime = 1.0;
  23520. Scene.MaxDeltaTime = 1000.0;
  23521. /** The distance in pixel that you have to move to prevent some events */
  23522. Scene.DragMovementThreshold = 10; // in pixels
  23523. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23524. Scene.LongPressDelay = 500; // in milliseconds
  23525. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23526. Scene.DoubleClickDelay = 300; // in milliseconds
  23527. /** If you need to check double click without raising a single click at first click, enable this flag */
  23528. Scene.ExclusiveDoubleClickMode = false;
  23529. return Scene;
  23530. }());
  23531. BABYLON.Scene = Scene;
  23532. })(BABYLON || (BABYLON = {}));
  23533. //# sourceMappingURL=babylon.scene.js.map
  23534. var BABYLON;
  23535. (function (BABYLON) {
  23536. /**
  23537. * Set of assets to keep when moving a scene into an asset container.
  23538. */
  23539. var KeepAssets = /** @class */ (function () {
  23540. function KeepAssets() {
  23541. /**
  23542. * Cameras to keep.
  23543. */
  23544. this.cameras = new Array();
  23545. /**
  23546. * Lights to keep.
  23547. */
  23548. this.lights = new Array();
  23549. /**
  23550. * Meshes to keep.
  23551. */
  23552. this.meshes = new Array();
  23553. /**
  23554. * Skeletons to keep.
  23555. */
  23556. this.skeletons = new Array();
  23557. /**
  23558. * ParticleSystems to keep.
  23559. */
  23560. this.particleSystems = new Array();
  23561. /**
  23562. * Animations to keep.
  23563. */
  23564. this.animations = new Array();
  23565. /**
  23566. * MultiMaterials to keep.
  23567. */
  23568. this.multiMaterials = new Array();
  23569. /**
  23570. * Materials to keep.
  23571. */
  23572. this.materials = new Array();
  23573. /**
  23574. * MorphTargetManagers to keep.
  23575. */
  23576. this.morphTargetManagers = new Array();
  23577. /**
  23578. * Geometries to keep.
  23579. */
  23580. this.geometries = new Array();
  23581. /**
  23582. * TransformNodes to keep.
  23583. */
  23584. this.transformNodes = new Array();
  23585. /**
  23586. * LensFlareSystems to keep.
  23587. */
  23588. this.lensFlareSystems = new Array();
  23589. /**
  23590. * ShadowGenerators to keep.
  23591. */
  23592. this.shadowGenerators = new Array();
  23593. /**
  23594. * ActionManagers to keep.
  23595. */
  23596. this.actionManagers = new Array();
  23597. /**
  23598. * Sounds to keep.
  23599. */
  23600. this.sounds = new Array();
  23601. }
  23602. return KeepAssets;
  23603. }());
  23604. BABYLON.KeepAssets = KeepAssets;
  23605. /**
  23606. * Container with a set of assets that can be added or removed from a scene.
  23607. */
  23608. var AssetContainer = /** @class */ (function () {
  23609. /**
  23610. * Instantiates an AssetContainer.
  23611. * @param scene The scene the AssetContainer belongs to.
  23612. */
  23613. function AssetContainer(scene) {
  23614. // Objects
  23615. /**
  23616. * Cameras populated in the container.
  23617. */
  23618. this.cameras = new Array();
  23619. /**
  23620. * Lights populated in the container.
  23621. */
  23622. this.lights = new Array();
  23623. /**
  23624. * Meshes populated in the container.
  23625. */
  23626. this.meshes = new Array();
  23627. /**
  23628. * Skeletons populated in the container.
  23629. */
  23630. this.skeletons = new Array();
  23631. /**
  23632. * ParticleSystems populated in the container.
  23633. */
  23634. this.particleSystems = new Array();
  23635. /**
  23636. * Animations populated in the container.
  23637. */
  23638. this.animations = new Array();
  23639. /**
  23640. * MultiMaterials populated in the container.
  23641. */
  23642. this.multiMaterials = new Array();
  23643. /**
  23644. * Materials populated in the container.
  23645. */
  23646. this.materials = new Array();
  23647. /**
  23648. * MorphTargetManagers populated in the container.
  23649. */
  23650. this.morphTargetManagers = new Array();
  23651. /**
  23652. * Geometries populated in the container.
  23653. */
  23654. this.geometries = new Array();
  23655. /**
  23656. * TransformNodes populated in the container.
  23657. */
  23658. this.transformNodes = new Array();
  23659. /**
  23660. * LensFlareSystems populated in the container.
  23661. */
  23662. this.lensFlareSystems = new Array();
  23663. /**
  23664. * ShadowGenerators populated in the container.
  23665. */
  23666. this.shadowGenerators = new Array();
  23667. /**
  23668. * ActionManagers populated in the container.
  23669. */
  23670. this.actionManagers = new Array();
  23671. /**
  23672. * Sounds populated in the container.
  23673. */
  23674. this.sounds = new Array();
  23675. this.scene = scene;
  23676. }
  23677. /**
  23678. * Adds all the assets from the container to the scene.
  23679. */
  23680. AssetContainer.prototype.addAllToScene = function () {
  23681. var _this = this;
  23682. this.cameras.forEach(function (o) {
  23683. _this.scene.addCamera(o);
  23684. });
  23685. this.lights.forEach(function (o) {
  23686. _this.scene.addLight(o);
  23687. });
  23688. this.meshes.forEach(function (o) {
  23689. _this.scene.addMesh(o);
  23690. });
  23691. this.skeletons.forEach(function (o) {
  23692. _this.scene.addSkeleton(o);
  23693. });
  23694. this.particleSystems.forEach(function (o) {
  23695. _this.scene.addParticleSystem(o);
  23696. });
  23697. this.animations.forEach(function (o) {
  23698. _this.scene.addAnimation(o);
  23699. });
  23700. this.multiMaterials.forEach(function (o) {
  23701. _this.scene.addMultiMaterial(o);
  23702. });
  23703. this.materials.forEach(function (o) {
  23704. _this.scene.addMaterial(o);
  23705. });
  23706. this.morphTargetManagers.forEach(function (o) {
  23707. _this.scene.addMorphTargetManager(o);
  23708. });
  23709. this.geometries.forEach(function (o) {
  23710. _this.scene.addGeometry(o);
  23711. });
  23712. this.transformNodes.forEach(function (o) {
  23713. _this.scene.addTransformNode(o);
  23714. });
  23715. this.lensFlareSystems.forEach(function (o) {
  23716. _this.scene.addLensFlareSystem(o);
  23717. });
  23718. this.actionManagers.forEach(function (o) {
  23719. _this.scene.addActionManager(o);
  23720. });
  23721. this.sounds.forEach(function (o) {
  23722. o.play();
  23723. o.autoplay = true;
  23724. _this.scene.mainSoundTrack.AddSound(o);
  23725. });
  23726. };
  23727. /**
  23728. * Removes all the assets in the container from the scene
  23729. */
  23730. AssetContainer.prototype.removeAllFromScene = function () {
  23731. var _this = this;
  23732. this.cameras.forEach(function (o) {
  23733. _this.scene.removeCamera(o);
  23734. });
  23735. this.lights.forEach(function (o) {
  23736. _this.scene.removeLight(o);
  23737. });
  23738. this.meshes.forEach(function (o) {
  23739. _this.scene.removeMesh(o);
  23740. });
  23741. this.skeletons.forEach(function (o) {
  23742. _this.scene.removeSkeleton(o);
  23743. });
  23744. this.particleSystems.forEach(function (o) {
  23745. _this.scene.removeParticleSystem(o);
  23746. });
  23747. this.animations.forEach(function (o) {
  23748. _this.scene.removeAnimation(o);
  23749. });
  23750. this.multiMaterials.forEach(function (o) {
  23751. _this.scene.removeMultiMaterial(o);
  23752. });
  23753. this.materials.forEach(function (o) {
  23754. _this.scene.removeMaterial(o);
  23755. });
  23756. this.morphTargetManagers.forEach(function (o) {
  23757. _this.scene.removeMorphTargetManager(o);
  23758. });
  23759. this.geometries.forEach(function (o) {
  23760. _this.scene.removeGeometry(o);
  23761. });
  23762. this.transformNodes.forEach(function (o) {
  23763. _this.scene.removeTransformNode(o);
  23764. });
  23765. this.lensFlareSystems.forEach(function (o) {
  23766. _this.scene.removeLensFlareSystem(o);
  23767. });
  23768. this.actionManagers.forEach(function (o) {
  23769. _this.scene.removeActionManager(o);
  23770. });
  23771. this.sounds.forEach(function (o) {
  23772. o.stop();
  23773. o.autoplay = false;
  23774. _this.scene.mainSoundTrack.RemoveSound(o);
  23775. });
  23776. };
  23777. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  23778. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  23779. var asset = sourceAssets_1[_i];
  23780. var move = true;
  23781. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  23782. var keepAsset = keepAssets_1[_a];
  23783. if (asset === keepAsset) {
  23784. move = false;
  23785. break;
  23786. }
  23787. }
  23788. if (move) {
  23789. targetAssets.push(asset);
  23790. }
  23791. }
  23792. };
  23793. /**
  23794. * Removes all the assets contained in the scene and adds them to the container.
  23795. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  23796. */
  23797. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  23798. if (keepAssets === undefined) {
  23799. keepAssets = new KeepAssets();
  23800. }
  23801. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  23802. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  23803. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  23804. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  23805. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  23806. Array.prototype.push.apply(this.animations, this.scene.animations);
  23807. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  23808. Array.prototype.push.apply(this.lights, this.scene.lights);
  23809. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  23810. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  23811. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  23812. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  23813. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  23814. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  23815. this.removeAllFromScene();
  23816. };
  23817. return AssetContainer;
  23818. }());
  23819. BABYLON.AssetContainer = AssetContainer;
  23820. })(BABYLON || (BABYLON = {}));
  23821. //# sourceMappingURL=babylon.assetContainer.js.map
  23822. var BABYLON;
  23823. (function (BABYLON) {
  23824. var Buffer = /** @class */ (function () {
  23825. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23826. if (instanced === void 0) { instanced = false; }
  23827. if (engine instanceof BABYLON.Mesh) {
  23828. this._engine = engine.getScene().getEngine();
  23829. }
  23830. else {
  23831. this._engine = engine;
  23832. }
  23833. this._updatable = updatable;
  23834. this._data = data;
  23835. this._strideSize = stride;
  23836. if (!postponeInternalCreation) {
  23837. this.create();
  23838. }
  23839. this._instanced = instanced;
  23840. this._instanceDivisor = instanced ? 1 : 0;
  23841. }
  23842. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23843. // a lot of these parameters are ignored as they are overriden by the buffer
  23844. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23845. };
  23846. // Properties
  23847. Buffer.prototype.isUpdatable = function () {
  23848. return this._updatable;
  23849. };
  23850. Buffer.prototype.getData = function () {
  23851. return this._data;
  23852. };
  23853. Buffer.prototype.getBuffer = function () {
  23854. return this._buffer;
  23855. };
  23856. Buffer.prototype.getStrideSize = function () {
  23857. return this._strideSize;
  23858. };
  23859. Buffer.prototype.getIsInstanced = function () {
  23860. return this._instanced;
  23861. };
  23862. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23863. get: function () {
  23864. return this._instanceDivisor;
  23865. },
  23866. set: function (value) {
  23867. this._instanceDivisor = value;
  23868. if (value == 0) {
  23869. this._instanced = false;
  23870. }
  23871. else {
  23872. this._instanced = true;
  23873. }
  23874. },
  23875. enumerable: true,
  23876. configurable: true
  23877. });
  23878. // Methods
  23879. Buffer.prototype.create = function (data) {
  23880. if (data === void 0) { data = null; }
  23881. if (!data && this._buffer) {
  23882. return; // nothing to do
  23883. }
  23884. data = data || this._data;
  23885. if (!data) {
  23886. return;
  23887. }
  23888. if (!this._buffer) {
  23889. if (this._updatable) {
  23890. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23891. this._data = data;
  23892. }
  23893. else {
  23894. this._buffer = this._engine.createVertexBuffer(data);
  23895. }
  23896. }
  23897. else if (this._updatable) {
  23898. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23899. this._data = data;
  23900. }
  23901. };
  23902. Buffer.prototype._rebuild = function () {
  23903. this._buffer = null;
  23904. this.create(this._data);
  23905. };
  23906. Buffer.prototype.update = function (data) {
  23907. this.create(data);
  23908. };
  23909. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23910. if (!this._buffer) {
  23911. return;
  23912. }
  23913. if (this._updatable) {
  23914. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23915. this._data = null;
  23916. }
  23917. };
  23918. Buffer.prototype.dispose = function () {
  23919. if (!this._buffer) {
  23920. return;
  23921. }
  23922. if (this._engine._releaseBuffer(this._buffer)) {
  23923. this._buffer = null;
  23924. }
  23925. };
  23926. return Buffer;
  23927. }());
  23928. BABYLON.Buffer = Buffer;
  23929. })(BABYLON || (BABYLON = {}));
  23930. //# sourceMappingURL=babylon.buffer.js.map
  23931. var BABYLON;
  23932. (function (BABYLON) {
  23933. var VertexBuffer = /** @class */ (function () {
  23934. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23935. if (!stride) {
  23936. // Deduce stride from kind
  23937. switch (kind) {
  23938. case VertexBuffer.PositionKind:
  23939. stride = 3;
  23940. break;
  23941. case VertexBuffer.NormalKind:
  23942. stride = 3;
  23943. break;
  23944. case VertexBuffer.UVKind:
  23945. case VertexBuffer.UV2Kind:
  23946. case VertexBuffer.UV3Kind:
  23947. case VertexBuffer.UV4Kind:
  23948. case VertexBuffer.UV5Kind:
  23949. case VertexBuffer.UV6Kind:
  23950. stride = 2;
  23951. break;
  23952. case VertexBuffer.TangentKind:
  23953. case VertexBuffer.ColorKind:
  23954. stride = 4;
  23955. break;
  23956. case VertexBuffer.MatricesIndicesKind:
  23957. case VertexBuffer.MatricesIndicesExtraKind:
  23958. stride = 4;
  23959. break;
  23960. case VertexBuffer.MatricesWeightsKind:
  23961. case VertexBuffer.MatricesWeightsExtraKind:
  23962. default:
  23963. stride = 4;
  23964. break;
  23965. }
  23966. }
  23967. if (data instanceof BABYLON.Buffer) {
  23968. if (!stride) {
  23969. stride = data.getStrideSize();
  23970. }
  23971. this._buffer = data;
  23972. this._ownsBuffer = false;
  23973. }
  23974. else {
  23975. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23976. this._ownsBuffer = true;
  23977. }
  23978. this._stride = stride;
  23979. this._offset = offset ? offset : 0;
  23980. this._size = size ? size : stride;
  23981. this._kind = kind;
  23982. }
  23983. VertexBuffer.prototype._rebuild = function () {
  23984. if (!this._buffer) {
  23985. return;
  23986. }
  23987. this._buffer._rebuild();
  23988. };
  23989. /**
  23990. * Returns the kind of the VertexBuffer (string).
  23991. */
  23992. VertexBuffer.prototype.getKind = function () {
  23993. return this._kind;
  23994. };
  23995. // Properties
  23996. /**
  23997. * Boolean : is the VertexBuffer updatable ?
  23998. */
  23999. VertexBuffer.prototype.isUpdatable = function () {
  24000. return this._buffer.isUpdatable();
  24001. };
  24002. /**
  24003. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24004. */
  24005. VertexBuffer.prototype.getData = function () {
  24006. return this._buffer.getData();
  24007. };
  24008. /**
  24009. * Returns the WebGLBuffer associated to the VertexBuffer.
  24010. */
  24011. VertexBuffer.prototype.getBuffer = function () {
  24012. return this._buffer.getBuffer();
  24013. };
  24014. /**
  24015. * Returns the stride of the VertexBuffer (integer).
  24016. */
  24017. VertexBuffer.prototype.getStrideSize = function () {
  24018. return this._stride;
  24019. };
  24020. /**
  24021. * Returns the offset (integer).
  24022. */
  24023. VertexBuffer.prototype.getOffset = function () {
  24024. return this._offset;
  24025. };
  24026. /**
  24027. * Returns the VertexBuffer total size (integer).
  24028. */
  24029. VertexBuffer.prototype.getSize = function () {
  24030. return this._size;
  24031. };
  24032. /**
  24033. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24034. */
  24035. VertexBuffer.prototype.getIsInstanced = function () {
  24036. return this._buffer.getIsInstanced();
  24037. };
  24038. /**
  24039. * Returns the instancing divisor, zero for non-instanced (integer).
  24040. */
  24041. VertexBuffer.prototype.getInstanceDivisor = function () {
  24042. return this._buffer.instanceDivisor;
  24043. };
  24044. // Methods
  24045. /**
  24046. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24047. * Returns the created WebGLBuffer.
  24048. */
  24049. VertexBuffer.prototype.create = function (data) {
  24050. return this._buffer.create(data);
  24051. };
  24052. /**
  24053. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24054. * This function will create a new buffer if the current one is not updatable
  24055. * Returns the updated WebGLBuffer.
  24056. */
  24057. VertexBuffer.prototype.update = function (data) {
  24058. return this._buffer.update(data);
  24059. };
  24060. /**
  24061. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24062. * Returns the directly updated WebGLBuffer.
  24063. */
  24064. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24065. return this._buffer.updateDirectly(data, offset);
  24066. };
  24067. /**
  24068. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24069. */
  24070. VertexBuffer.prototype.dispose = function () {
  24071. if (this._ownsBuffer) {
  24072. this._buffer.dispose();
  24073. }
  24074. };
  24075. Object.defineProperty(VertexBuffer, "PositionKind", {
  24076. get: function () {
  24077. return VertexBuffer._PositionKind;
  24078. },
  24079. enumerable: true,
  24080. configurable: true
  24081. });
  24082. Object.defineProperty(VertexBuffer, "NormalKind", {
  24083. get: function () {
  24084. return VertexBuffer._NormalKind;
  24085. },
  24086. enumerable: true,
  24087. configurable: true
  24088. });
  24089. Object.defineProperty(VertexBuffer, "TangentKind", {
  24090. get: function () {
  24091. return VertexBuffer._TangentKind;
  24092. },
  24093. enumerable: true,
  24094. configurable: true
  24095. });
  24096. Object.defineProperty(VertexBuffer, "UVKind", {
  24097. get: function () {
  24098. return VertexBuffer._UVKind;
  24099. },
  24100. enumerable: true,
  24101. configurable: true
  24102. });
  24103. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24104. get: function () {
  24105. return VertexBuffer._UV2Kind;
  24106. },
  24107. enumerable: true,
  24108. configurable: true
  24109. });
  24110. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24111. get: function () {
  24112. return VertexBuffer._UV3Kind;
  24113. },
  24114. enumerable: true,
  24115. configurable: true
  24116. });
  24117. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24118. get: function () {
  24119. return VertexBuffer._UV4Kind;
  24120. },
  24121. enumerable: true,
  24122. configurable: true
  24123. });
  24124. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24125. get: function () {
  24126. return VertexBuffer._UV5Kind;
  24127. },
  24128. enumerable: true,
  24129. configurable: true
  24130. });
  24131. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24132. get: function () {
  24133. return VertexBuffer._UV6Kind;
  24134. },
  24135. enumerable: true,
  24136. configurable: true
  24137. });
  24138. Object.defineProperty(VertexBuffer, "ColorKind", {
  24139. get: function () {
  24140. return VertexBuffer._ColorKind;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24146. get: function () {
  24147. return VertexBuffer._MatricesIndicesKind;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24153. get: function () {
  24154. return VertexBuffer._MatricesWeightsKind;
  24155. },
  24156. enumerable: true,
  24157. configurable: true
  24158. });
  24159. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24160. get: function () {
  24161. return VertexBuffer._MatricesIndicesExtraKind;
  24162. },
  24163. enumerable: true,
  24164. configurable: true
  24165. });
  24166. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24167. get: function () {
  24168. return VertexBuffer._MatricesWeightsExtraKind;
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. // Enums
  24174. VertexBuffer._PositionKind = "position";
  24175. VertexBuffer._NormalKind = "normal";
  24176. VertexBuffer._TangentKind = "tangent";
  24177. VertexBuffer._UVKind = "uv";
  24178. VertexBuffer._UV2Kind = "uv2";
  24179. VertexBuffer._UV3Kind = "uv3";
  24180. VertexBuffer._UV4Kind = "uv4";
  24181. VertexBuffer._UV5Kind = "uv5";
  24182. VertexBuffer._UV6Kind = "uv6";
  24183. VertexBuffer._ColorKind = "color";
  24184. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24185. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24186. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24187. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24188. return VertexBuffer;
  24189. }());
  24190. BABYLON.VertexBuffer = VertexBuffer;
  24191. })(BABYLON || (BABYLON = {}));
  24192. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24193. var BABYLON;
  24194. (function (BABYLON) {
  24195. /**
  24196. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24197. */
  24198. var DummyInternalTextureTracker = /** @class */ (function () {
  24199. function DummyInternalTextureTracker() {
  24200. /**
  24201. * Gets or set the previous tracker in the list
  24202. */
  24203. this.previous = null;
  24204. /**
  24205. * Gets or set the next tracker in the list
  24206. */
  24207. this.next = null;
  24208. }
  24209. return DummyInternalTextureTracker;
  24210. }());
  24211. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24212. })(BABYLON || (BABYLON = {}));
  24213. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24214. var BABYLON;
  24215. (function (BABYLON) {
  24216. /**
  24217. * Class used to store data associated with WebGL texture data for the engine
  24218. * This class should not be used directly
  24219. */
  24220. var InternalTexture = /** @class */ (function () {
  24221. /**
  24222. * Creates a new InternalTexture
  24223. * @param engine defines the engine to use
  24224. * @param dataSource defines the type of data that will be used
  24225. */
  24226. function InternalTexture(engine, dataSource) {
  24227. /**
  24228. * Observable called when the texture is loaded
  24229. */
  24230. this.onLoadedObservable = new BABYLON.Observable();
  24231. /**
  24232. * Gets or set the previous tracker in the list
  24233. */
  24234. this.previous = null;
  24235. /**
  24236. * Gets or set the next tracker in the list
  24237. */
  24238. this.next = null;
  24239. // Private
  24240. /** @ignore */
  24241. this._initialSlot = -1;
  24242. /** @ignore */
  24243. this._designatedSlot = -1;
  24244. /** @ignore */
  24245. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24246. /** @ignore */
  24247. this._references = 1;
  24248. this._engine = engine;
  24249. this._dataSource = dataSource;
  24250. this._webGLTexture = engine._createTexture();
  24251. }
  24252. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24253. /**
  24254. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24255. */
  24256. get: function () {
  24257. return this._dataSource;
  24258. },
  24259. enumerable: true,
  24260. configurable: true
  24261. });
  24262. /**
  24263. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24264. */
  24265. InternalTexture.prototype.incrementReferences = function () {
  24266. this._references++;
  24267. };
  24268. /**
  24269. * Change the size of the texture (not the size of the content)
  24270. * @param width defines the new width
  24271. * @param height defines the new height
  24272. * @param depth defines the new depth (1 by default)
  24273. */
  24274. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24275. if (depth === void 0) { depth = 1; }
  24276. this.width = width;
  24277. this.height = height;
  24278. this.depth = depth;
  24279. this.baseWidth = width;
  24280. this.baseHeight = height;
  24281. this.baseDepth = depth;
  24282. this._size = width * height * depth;
  24283. };
  24284. /** @ignore */
  24285. InternalTexture.prototype._rebuild = function () {
  24286. var _this = this;
  24287. var proxy;
  24288. this.isReady = false;
  24289. this._cachedCoordinatesMode = null;
  24290. this._cachedWrapU = null;
  24291. this._cachedWrapV = null;
  24292. this._cachedAnisotropicFilteringLevel = null;
  24293. switch (this._dataSource) {
  24294. case InternalTexture.DATASOURCE_TEMP:
  24295. return;
  24296. case InternalTexture.DATASOURCE_URL:
  24297. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24298. _this.isReady = true;
  24299. }, null, this._buffer, undefined, this.format);
  24300. proxy._swapAndDie(this);
  24301. return;
  24302. case InternalTexture.DATASOURCE_RAW:
  24303. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24304. proxy._swapAndDie(this);
  24305. this.isReady = true;
  24306. return;
  24307. case InternalTexture.DATASOURCE_RAW3D:
  24308. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24309. proxy._swapAndDie(this);
  24310. this.isReady = true;
  24311. return;
  24312. case InternalTexture.DATASOURCE_DYNAMIC:
  24313. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24314. proxy._swapAndDie(this);
  24315. // The engine will make sure to update content so no need to flag it as isReady = true
  24316. return;
  24317. case InternalTexture.DATASOURCE_RENDERTARGET:
  24318. var options = new BABYLON.RenderTargetCreationOptions();
  24319. options.generateDepthBuffer = this._generateDepthBuffer;
  24320. options.generateMipMaps = this.generateMipMaps;
  24321. options.generateStencilBuffer = this._generateStencilBuffer;
  24322. options.samplingMode = this.samplingMode;
  24323. options.type = this.type;
  24324. if (this.isCube) {
  24325. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24326. }
  24327. else {
  24328. var size = {
  24329. width: this.width,
  24330. height: this.height
  24331. };
  24332. proxy = this._engine.createRenderTargetTexture(size, options);
  24333. }
  24334. proxy._swapAndDie(this);
  24335. this.isReady = true;
  24336. return;
  24337. case InternalTexture.DATASOURCE_CUBE:
  24338. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24339. _this.isReady = true;
  24340. }, null, this.format, this._extension);
  24341. proxy._swapAndDie(this);
  24342. return;
  24343. case InternalTexture.DATASOURCE_CUBERAW:
  24344. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24345. proxy._swapAndDie(this);
  24346. this.isReady = true;
  24347. return;
  24348. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24349. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24350. if (proxy) {
  24351. proxy._swapAndDie(_this);
  24352. }
  24353. _this.isReady = true;
  24354. }, null, this.format, this._extension);
  24355. return;
  24356. }
  24357. };
  24358. InternalTexture.prototype._swapAndDie = function (target) {
  24359. target._webGLTexture = this._webGLTexture;
  24360. if (this._framebuffer) {
  24361. target._framebuffer = this._framebuffer;
  24362. }
  24363. if (this._depthStencilBuffer) {
  24364. target._depthStencilBuffer = this._depthStencilBuffer;
  24365. }
  24366. if (this._lodTextureHigh) {
  24367. if (target._lodTextureHigh) {
  24368. target._lodTextureHigh.dispose();
  24369. }
  24370. target._lodTextureHigh = this._lodTextureHigh;
  24371. }
  24372. if (this._lodTextureMid) {
  24373. if (target._lodTextureMid) {
  24374. target._lodTextureMid.dispose();
  24375. }
  24376. target._lodTextureMid = this._lodTextureMid;
  24377. }
  24378. if (this._lodTextureLow) {
  24379. if (target._lodTextureLow) {
  24380. target._lodTextureLow.dispose();
  24381. }
  24382. target._lodTextureLow = this._lodTextureLow;
  24383. }
  24384. var cache = this._engine.getLoadedTexturesCache();
  24385. var index = cache.indexOf(this);
  24386. if (index !== -1) {
  24387. cache.splice(index, 1);
  24388. }
  24389. };
  24390. /**
  24391. * Dispose the current allocated resources
  24392. */
  24393. InternalTexture.prototype.dispose = function () {
  24394. if (!this._webGLTexture) {
  24395. return;
  24396. }
  24397. this._references--;
  24398. if (this._references === 0) {
  24399. this._engine._releaseTexture(this);
  24400. this._webGLTexture = null;
  24401. this.previous = null;
  24402. this.next = null;
  24403. }
  24404. };
  24405. /**
  24406. * The source of the texture data is unknown
  24407. */
  24408. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24409. /**
  24410. * Texture data comes from an URL
  24411. */
  24412. InternalTexture.DATASOURCE_URL = 1;
  24413. /**
  24414. * Texture data is only used for temporary storage
  24415. */
  24416. InternalTexture.DATASOURCE_TEMP = 2;
  24417. /**
  24418. * Texture data comes from raw data (ArrayBuffer)
  24419. */
  24420. InternalTexture.DATASOURCE_RAW = 3;
  24421. /**
  24422. * Texture content is dynamic (video or dynamic texture)
  24423. */
  24424. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24425. /**
  24426. * Texture content is generated by rendering to it
  24427. */
  24428. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24429. /**
  24430. * Texture content is part of a multi render target process
  24431. */
  24432. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24433. /**
  24434. * Texture data comes from a cube data file
  24435. */
  24436. InternalTexture.DATASOURCE_CUBE = 7;
  24437. /**
  24438. * Texture data comes from a raw cube data
  24439. */
  24440. InternalTexture.DATASOURCE_CUBERAW = 8;
  24441. /**
  24442. * Texture data come from a prefiltered cube data file
  24443. */
  24444. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24445. /**
  24446. * Texture content is raw 3D data
  24447. */
  24448. InternalTexture.DATASOURCE_RAW3D = 10;
  24449. return InternalTexture;
  24450. }());
  24451. BABYLON.InternalTexture = InternalTexture;
  24452. })(BABYLON || (BABYLON = {}));
  24453. //# sourceMappingURL=babylon.internalTexture.js.map
  24454. var BABYLON;
  24455. (function (BABYLON) {
  24456. var BaseTexture = /** @class */ (function () {
  24457. function BaseTexture(scene) {
  24458. this._hasAlpha = false;
  24459. this.getAlphaFromRGB = false;
  24460. this.level = 1;
  24461. this.coordinatesIndex = 0;
  24462. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24463. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24464. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24465. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24466. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24467. this.isCube = false;
  24468. this.is3D = false;
  24469. this.gammaSpace = true;
  24470. this.invertZ = false;
  24471. this.lodLevelInAlpha = false;
  24472. this.lodGenerationOffset = 0.0;
  24473. this.lodGenerationScale = 0.8;
  24474. this.isRenderTarget = false;
  24475. this.animations = new Array();
  24476. /**
  24477. * An event triggered when the texture is disposed.
  24478. * @type {BABYLON.Observable}
  24479. */
  24480. this.onDisposeObservable = new BABYLON.Observable();
  24481. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24482. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24483. if (this._scene) {
  24484. this._scene.textures.push(this);
  24485. }
  24486. this._uid = null;
  24487. }
  24488. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24489. get: function () {
  24490. return this._hasAlpha;
  24491. },
  24492. set: function (value) {
  24493. if (this._hasAlpha === value) {
  24494. return;
  24495. }
  24496. this._hasAlpha = value;
  24497. if (this._scene) {
  24498. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24499. }
  24500. },
  24501. enumerable: true,
  24502. configurable: true
  24503. });
  24504. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24505. get: function () {
  24506. return this._coordinatesMode;
  24507. },
  24508. set: function (value) {
  24509. if (this._coordinatesMode === value) {
  24510. return;
  24511. }
  24512. this._coordinatesMode = value;
  24513. if (this._scene) {
  24514. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24515. }
  24516. },
  24517. enumerable: true,
  24518. configurable: true
  24519. });
  24520. Object.defineProperty(BaseTexture.prototype, "uid", {
  24521. get: function () {
  24522. if (!this._uid) {
  24523. this._uid = BABYLON.Tools.RandomId();
  24524. }
  24525. return this._uid;
  24526. },
  24527. enumerable: true,
  24528. configurable: true
  24529. });
  24530. BaseTexture.prototype.toString = function () {
  24531. return this.name;
  24532. };
  24533. BaseTexture.prototype.getClassName = function () {
  24534. return "BaseTexture";
  24535. };
  24536. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24537. set: function (callback) {
  24538. if (this._onDisposeObserver) {
  24539. this.onDisposeObservable.remove(this._onDisposeObserver);
  24540. }
  24541. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24542. },
  24543. enumerable: true,
  24544. configurable: true
  24545. });
  24546. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24547. get: function () {
  24548. return true;
  24549. },
  24550. enumerable: true,
  24551. configurable: true
  24552. });
  24553. BaseTexture.prototype.getScene = function () {
  24554. return this._scene;
  24555. };
  24556. BaseTexture.prototype.getTextureMatrix = function () {
  24557. return BABYLON.Matrix.IdentityReadOnly;
  24558. };
  24559. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24560. return BABYLON.Matrix.IdentityReadOnly;
  24561. };
  24562. BaseTexture.prototype.getInternalTexture = function () {
  24563. return this._texture;
  24564. };
  24565. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24566. return !this.isBlocking || this.isReady();
  24567. };
  24568. BaseTexture.prototype.isReady = function () {
  24569. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24570. this.delayLoad();
  24571. return false;
  24572. }
  24573. if (this._texture) {
  24574. return this._texture.isReady;
  24575. }
  24576. return false;
  24577. };
  24578. BaseTexture.prototype.getSize = function () {
  24579. if (this._texture && this._texture.width) {
  24580. return new BABYLON.Size(this._texture.width, this._texture.height);
  24581. }
  24582. if (this._texture && this._texture._size) {
  24583. return new BABYLON.Size(this._texture._size, this._texture._size);
  24584. }
  24585. return BABYLON.Size.Zero();
  24586. };
  24587. BaseTexture.prototype.getBaseSize = function () {
  24588. if (!this.isReady() || !this._texture)
  24589. return BABYLON.Size.Zero();
  24590. if (this._texture._size) {
  24591. return new BABYLON.Size(this._texture._size, this._texture._size);
  24592. }
  24593. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24594. };
  24595. BaseTexture.prototype.scale = function (ratio) {
  24596. };
  24597. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24598. get: function () {
  24599. return false;
  24600. },
  24601. enumerable: true,
  24602. configurable: true
  24603. });
  24604. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24605. if (!this._scene) {
  24606. return null;
  24607. }
  24608. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24609. for (var index = 0; index < texturesCache.length; index++) {
  24610. var texturesCacheEntry = texturesCache[index];
  24611. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24612. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24613. texturesCacheEntry.incrementReferences();
  24614. return texturesCacheEntry;
  24615. }
  24616. }
  24617. }
  24618. return null;
  24619. };
  24620. BaseTexture.prototype._rebuild = function () {
  24621. };
  24622. BaseTexture.prototype.delayLoad = function () {
  24623. };
  24624. BaseTexture.prototype.clone = function () {
  24625. return null;
  24626. };
  24627. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24628. get: function () {
  24629. if (!this._texture) {
  24630. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24631. }
  24632. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24633. },
  24634. enumerable: true,
  24635. configurable: true
  24636. });
  24637. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24638. get: function () {
  24639. if (!this._texture) {
  24640. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24641. }
  24642. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24643. },
  24644. enumerable: true,
  24645. configurable: true
  24646. });
  24647. BaseTexture.prototype.readPixels = function (faceIndex) {
  24648. if (faceIndex === void 0) { faceIndex = 0; }
  24649. if (!this._texture) {
  24650. return null;
  24651. }
  24652. var size = this.getSize();
  24653. var scene = this.getScene();
  24654. if (!scene) {
  24655. return null;
  24656. }
  24657. var engine = scene.getEngine();
  24658. if (this._texture.isCube) {
  24659. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24660. }
  24661. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24662. };
  24663. BaseTexture.prototype.releaseInternalTexture = function () {
  24664. if (this._texture) {
  24665. this._texture.dispose();
  24666. this._texture = null;
  24667. }
  24668. };
  24669. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24670. get: function () {
  24671. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24672. return null;
  24673. }
  24674. if (!this._texture._sphericalPolynomial) {
  24675. this._texture._sphericalPolynomial =
  24676. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24677. }
  24678. return this._texture._sphericalPolynomial;
  24679. },
  24680. set: function (value) {
  24681. if (this._texture) {
  24682. this._texture._sphericalPolynomial = value;
  24683. }
  24684. },
  24685. enumerable: true,
  24686. configurable: true
  24687. });
  24688. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24689. get: function () {
  24690. if (this._texture) {
  24691. return this._texture._lodTextureHigh;
  24692. }
  24693. return null;
  24694. },
  24695. enumerable: true,
  24696. configurable: true
  24697. });
  24698. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24699. get: function () {
  24700. if (this._texture) {
  24701. return this._texture._lodTextureMid;
  24702. }
  24703. return null;
  24704. },
  24705. enumerable: true,
  24706. configurable: true
  24707. });
  24708. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24709. get: function () {
  24710. if (this._texture) {
  24711. return this._texture._lodTextureLow;
  24712. }
  24713. return null;
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. BaseTexture.prototype.dispose = function () {
  24719. if (!this._scene) {
  24720. return;
  24721. }
  24722. // Animations
  24723. this._scene.stopAnimation(this);
  24724. // Remove from scene
  24725. this._scene._removePendingData(this);
  24726. var index = this._scene.textures.indexOf(this);
  24727. if (index >= 0) {
  24728. this._scene.textures.splice(index, 1);
  24729. }
  24730. if (this._texture === undefined) {
  24731. return;
  24732. }
  24733. // Release
  24734. this.releaseInternalTexture();
  24735. // Callback
  24736. this.onDisposeObservable.notifyObservers(this);
  24737. this.onDisposeObservable.clear();
  24738. };
  24739. BaseTexture.prototype.serialize = function () {
  24740. if (!this.name) {
  24741. return null;
  24742. }
  24743. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24744. // Animations
  24745. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24746. return serializationObject;
  24747. };
  24748. BaseTexture.WhenAllReady = function (textures, callback) {
  24749. var numRemaining = textures.length;
  24750. if (numRemaining === 0) {
  24751. callback();
  24752. return;
  24753. }
  24754. var _loop_1 = function () {
  24755. texture = textures[i];
  24756. if (texture.isReady()) {
  24757. if (--numRemaining === 0) {
  24758. callback();
  24759. }
  24760. }
  24761. else {
  24762. onLoadObservable = texture.onLoadObservable;
  24763. var onLoadCallback_1 = function () {
  24764. onLoadObservable.removeCallback(onLoadCallback_1);
  24765. if (--numRemaining === 0) {
  24766. callback();
  24767. }
  24768. };
  24769. onLoadObservable.add(onLoadCallback_1);
  24770. }
  24771. };
  24772. var texture, onLoadObservable;
  24773. for (var i = 0; i < textures.length; i++) {
  24774. _loop_1();
  24775. }
  24776. };
  24777. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24778. __decorate([
  24779. BABYLON.serialize()
  24780. ], BaseTexture.prototype, "name", void 0);
  24781. __decorate([
  24782. BABYLON.serialize("hasAlpha")
  24783. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24784. __decorate([
  24785. BABYLON.serialize()
  24786. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24787. __decorate([
  24788. BABYLON.serialize()
  24789. ], BaseTexture.prototype, "level", void 0);
  24790. __decorate([
  24791. BABYLON.serialize()
  24792. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24793. __decorate([
  24794. BABYLON.serialize("coordinatesMode")
  24795. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24796. __decorate([
  24797. BABYLON.serialize()
  24798. ], BaseTexture.prototype, "wrapU", void 0);
  24799. __decorate([
  24800. BABYLON.serialize()
  24801. ], BaseTexture.prototype, "wrapV", void 0);
  24802. __decorate([
  24803. BABYLON.serialize()
  24804. ], BaseTexture.prototype, "wrapR", void 0);
  24805. __decorate([
  24806. BABYLON.serialize()
  24807. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24808. __decorate([
  24809. BABYLON.serialize()
  24810. ], BaseTexture.prototype, "isCube", void 0);
  24811. __decorate([
  24812. BABYLON.serialize()
  24813. ], BaseTexture.prototype, "is3D", void 0);
  24814. __decorate([
  24815. BABYLON.serialize()
  24816. ], BaseTexture.prototype, "gammaSpace", void 0);
  24817. __decorate([
  24818. BABYLON.serialize()
  24819. ], BaseTexture.prototype, "invertZ", void 0);
  24820. __decorate([
  24821. BABYLON.serialize()
  24822. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24823. __decorate([
  24824. BABYLON.serialize()
  24825. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24826. __decorate([
  24827. BABYLON.serialize()
  24828. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24829. __decorate([
  24830. BABYLON.serialize()
  24831. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24832. return BaseTexture;
  24833. }());
  24834. BABYLON.BaseTexture = BaseTexture;
  24835. })(BABYLON || (BABYLON = {}));
  24836. //# sourceMappingURL=babylon.baseTexture.js.map
  24837. var BABYLON;
  24838. (function (BABYLON) {
  24839. var Texture = /** @class */ (function (_super) {
  24840. __extends(Texture, _super);
  24841. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24842. if (noMipmap === void 0) { noMipmap = false; }
  24843. if (invertY === void 0) { invertY = true; }
  24844. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24845. if (onLoad === void 0) { onLoad = null; }
  24846. if (onError === void 0) { onError = null; }
  24847. if (buffer === void 0) { buffer = null; }
  24848. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24849. var _this = _super.call(this, scene) || this;
  24850. _this.uOffset = 0;
  24851. _this.vOffset = 0;
  24852. _this.uScale = 1.0;
  24853. _this.vScale = 1.0;
  24854. _this.uAng = 0;
  24855. _this.vAng = 0;
  24856. _this.wAng = 0;
  24857. _this._isBlocking = true;
  24858. _this.name = url || "";
  24859. _this.url = url;
  24860. _this._noMipmap = noMipmap;
  24861. _this._invertY = invertY;
  24862. _this._samplingMode = samplingMode;
  24863. _this._buffer = buffer;
  24864. _this._deleteBuffer = deleteBuffer;
  24865. if (format) {
  24866. _this._format = format;
  24867. }
  24868. scene = _this.getScene();
  24869. if (!scene) {
  24870. return _this;
  24871. }
  24872. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24873. var load = function () {
  24874. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24875. _this.onLoadObservable.notifyObservers(_this);
  24876. }
  24877. if (onLoad) {
  24878. onLoad();
  24879. }
  24880. if (!_this.isBlocking && scene) {
  24881. scene.resetCachedMaterial();
  24882. }
  24883. };
  24884. if (!_this.url) {
  24885. _this._delayedOnLoad = load;
  24886. _this._delayedOnError = onError;
  24887. return _this;
  24888. }
  24889. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24890. if (!_this._texture) {
  24891. if (!scene.useDelayedTextureLoading) {
  24892. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24893. if (deleteBuffer) {
  24894. delete _this._buffer;
  24895. }
  24896. }
  24897. else {
  24898. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24899. _this._delayedOnLoad = load;
  24900. _this._delayedOnError = onError;
  24901. }
  24902. }
  24903. else {
  24904. if (_this._texture.isReady) {
  24905. BABYLON.Tools.SetImmediate(function () { return load(); });
  24906. }
  24907. else {
  24908. _this._texture.onLoadedObservable.add(load);
  24909. }
  24910. }
  24911. return _this;
  24912. }
  24913. Object.defineProperty(Texture.prototype, "noMipmap", {
  24914. get: function () {
  24915. return this._noMipmap;
  24916. },
  24917. enumerable: true,
  24918. configurable: true
  24919. });
  24920. Object.defineProperty(Texture.prototype, "isBlocking", {
  24921. get: function () {
  24922. return this._isBlocking;
  24923. },
  24924. set: function (value) {
  24925. this._isBlocking = value;
  24926. },
  24927. enumerable: true,
  24928. configurable: true
  24929. });
  24930. Object.defineProperty(Texture.prototype, "samplingMode", {
  24931. get: function () {
  24932. return this._samplingMode;
  24933. },
  24934. enumerable: true,
  24935. configurable: true
  24936. });
  24937. Texture.prototype.updateURL = function (url) {
  24938. this.url = url;
  24939. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24940. this.delayLoad();
  24941. };
  24942. Texture.prototype.delayLoad = function () {
  24943. var _this = this;
  24944. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24945. return;
  24946. }
  24947. var scene = this.getScene();
  24948. if (!scene) {
  24949. return;
  24950. }
  24951. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24952. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24953. if (!this._texture) {
  24954. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24955. if (this._deleteBuffer) {
  24956. delete this._buffer;
  24957. }
  24958. }
  24959. else {
  24960. if (this._texture.isReady) {
  24961. BABYLON.Tools.SetImmediate(function () {
  24962. if (!_this._delayedOnLoad) {
  24963. return;
  24964. }
  24965. _this._delayedOnLoad();
  24966. });
  24967. }
  24968. else {
  24969. if (this._delayedOnLoad) {
  24970. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24971. }
  24972. }
  24973. }
  24974. };
  24975. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24976. if (!this._texture) {
  24977. return;
  24978. }
  24979. var scene = this.getScene();
  24980. if (!scene) {
  24981. return;
  24982. }
  24983. this._samplingMode = samplingMode;
  24984. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24985. };
  24986. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24987. x *= this.uScale;
  24988. y *= this.vScale;
  24989. x -= 0.5 * this.uScale;
  24990. y -= 0.5 * this.vScale;
  24991. z -= 0.5;
  24992. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24993. t.x += 0.5 * this.uScale + this.uOffset;
  24994. t.y += 0.5 * this.vScale + this.vOffset;
  24995. t.z += 0.5;
  24996. };
  24997. Texture.prototype.getTextureMatrix = function () {
  24998. var _this = this;
  24999. if (this.uOffset === this._cachedUOffset &&
  25000. this.vOffset === this._cachedVOffset &&
  25001. this.uScale === this._cachedUScale &&
  25002. this.vScale === this._cachedVScale &&
  25003. this.uAng === this._cachedUAng &&
  25004. this.vAng === this._cachedVAng &&
  25005. this.wAng === this._cachedWAng) {
  25006. return this._cachedTextureMatrix;
  25007. }
  25008. this._cachedUOffset = this.uOffset;
  25009. this._cachedVOffset = this.vOffset;
  25010. this._cachedUScale = this.uScale;
  25011. this._cachedVScale = this.vScale;
  25012. this._cachedUAng = this.uAng;
  25013. this._cachedVAng = this.vAng;
  25014. this._cachedWAng = this.wAng;
  25015. if (!this._cachedTextureMatrix) {
  25016. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25017. this._rowGenerationMatrix = new BABYLON.Matrix();
  25018. this._t0 = BABYLON.Vector3.Zero();
  25019. this._t1 = BABYLON.Vector3.Zero();
  25020. this._t2 = BABYLON.Vector3.Zero();
  25021. }
  25022. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25023. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25024. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25025. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25026. this._t1.subtractInPlace(this._t0);
  25027. this._t2.subtractInPlace(this._t0);
  25028. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25029. this._cachedTextureMatrix.m[0] = this._t1.x;
  25030. this._cachedTextureMatrix.m[1] = this._t1.y;
  25031. this._cachedTextureMatrix.m[2] = this._t1.z;
  25032. this._cachedTextureMatrix.m[4] = this._t2.x;
  25033. this._cachedTextureMatrix.m[5] = this._t2.y;
  25034. this._cachedTextureMatrix.m[6] = this._t2.z;
  25035. this._cachedTextureMatrix.m[8] = this._t0.x;
  25036. this._cachedTextureMatrix.m[9] = this._t0.y;
  25037. this._cachedTextureMatrix.m[10] = this._t0.z;
  25038. var scene = this.getScene();
  25039. if (!scene) {
  25040. return this._cachedTextureMatrix;
  25041. }
  25042. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25043. return mat.hasTexture(_this);
  25044. });
  25045. return this._cachedTextureMatrix;
  25046. };
  25047. Texture.prototype.getReflectionTextureMatrix = function () {
  25048. var _this = this;
  25049. var scene = this.getScene();
  25050. if (!scene) {
  25051. return this._cachedTextureMatrix;
  25052. }
  25053. if (this.uOffset === this._cachedUOffset &&
  25054. this.vOffset === this._cachedVOffset &&
  25055. this.uScale === this._cachedUScale &&
  25056. this.vScale === this._cachedVScale &&
  25057. this.coordinatesMode === this._cachedCoordinatesMode) {
  25058. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25059. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25060. return this._cachedTextureMatrix;
  25061. }
  25062. }
  25063. else {
  25064. return this._cachedTextureMatrix;
  25065. }
  25066. }
  25067. if (!this._cachedTextureMatrix) {
  25068. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25069. }
  25070. if (!this._projectionModeMatrix) {
  25071. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25072. }
  25073. this._cachedUOffset = this.uOffset;
  25074. this._cachedVOffset = this.vOffset;
  25075. this._cachedUScale = this.uScale;
  25076. this._cachedVScale = this.vScale;
  25077. this._cachedCoordinatesMode = this.coordinatesMode;
  25078. switch (this.coordinatesMode) {
  25079. case Texture.PLANAR_MODE:
  25080. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25081. this._cachedTextureMatrix[0] = this.uScale;
  25082. this._cachedTextureMatrix[5] = this.vScale;
  25083. this._cachedTextureMatrix[12] = this.uOffset;
  25084. this._cachedTextureMatrix[13] = this.vOffset;
  25085. break;
  25086. case Texture.PROJECTION_MODE:
  25087. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25088. this._projectionModeMatrix.m[0] = 0.5;
  25089. this._projectionModeMatrix.m[5] = -0.5;
  25090. this._projectionModeMatrix.m[10] = 0.0;
  25091. this._projectionModeMatrix.m[12] = 0.5;
  25092. this._projectionModeMatrix.m[13] = 0.5;
  25093. this._projectionModeMatrix.m[14] = 1.0;
  25094. this._projectionModeMatrix.m[15] = 1.0;
  25095. var projectionMatrix = scene.getProjectionMatrix();
  25096. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25097. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25098. break;
  25099. default:
  25100. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25101. break;
  25102. }
  25103. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25104. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25105. });
  25106. return this._cachedTextureMatrix;
  25107. };
  25108. Texture.prototype.clone = function () {
  25109. var _this = this;
  25110. return BABYLON.SerializationHelper.Clone(function () {
  25111. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25112. }, this);
  25113. };
  25114. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25115. get: function () {
  25116. if (!this._onLoadObservable) {
  25117. this._onLoadObservable = new BABYLON.Observable();
  25118. }
  25119. return this._onLoadObservable;
  25120. },
  25121. enumerable: true,
  25122. configurable: true
  25123. });
  25124. Texture.prototype.serialize = function () {
  25125. var serializationObject = _super.prototype.serialize.call(this);
  25126. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25127. serializationObject.base64String = this._buffer;
  25128. serializationObject.name = serializationObject.name.replace("data:", "");
  25129. }
  25130. return serializationObject;
  25131. };
  25132. Texture.prototype.getClassName = function () {
  25133. return "Texture";
  25134. };
  25135. Texture.prototype.dispose = function () {
  25136. _super.prototype.dispose.call(this);
  25137. if (this.onLoadObservable) {
  25138. this.onLoadObservable.clear();
  25139. this._onLoadObservable = null;
  25140. }
  25141. this._delayedOnLoad = null;
  25142. this._delayedOnError = null;
  25143. };
  25144. // Statics
  25145. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25146. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25147. if (onLoad === void 0) { onLoad = null; }
  25148. if (onError === void 0) { onError = null; }
  25149. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25150. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25151. };
  25152. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25153. if (parsedTexture.customType) {
  25154. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25155. // Update Sampling Mode
  25156. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25157. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25158. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25159. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25160. }
  25161. }
  25162. return parsedCustomTexture;
  25163. }
  25164. if (parsedTexture.isCube) {
  25165. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25166. }
  25167. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25168. return null;
  25169. }
  25170. var texture = BABYLON.SerializationHelper.Parse(function () {
  25171. var generateMipMaps = true;
  25172. if (parsedTexture.noMipmap) {
  25173. generateMipMaps = false;
  25174. }
  25175. if (parsedTexture.mirrorPlane) {
  25176. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25177. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25178. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25179. return mirrorTexture;
  25180. }
  25181. else if (parsedTexture.isRenderTarget) {
  25182. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25183. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25184. return renderTargetTexture;
  25185. }
  25186. else {
  25187. var texture;
  25188. if (parsedTexture.base64String) {
  25189. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25190. }
  25191. else {
  25192. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25193. }
  25194. return texture;
  25195. }
  25196. }, parsedTexture, scene);
  25197. // Update Sampling Mode
  25198. if (parsedTexture.samplingMode) {
  25199. var sampling = parsedTexture.samplingMode;
  25200. if (texture._samplingMode !== sampling) {
  25201. texture.updateSamplingMode(sampling);
  25202. }
  25203. }
  25204. // Animations
  25205. if (parsedTexture.animations) {
  25206. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25207. var parsedAnimation = parsedTexture.animations[animationIndex];
  25208. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25209. }
  25210. }
  25211. return texture;
  25212. };
  25213. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25214. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25215. if (noMipmap === void 0) { noMipmap = false; }
  25216. if (invertY === void 0) { invertY = true; }
  25217. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25218. if (onLoad === void 0) { onLoad = null; }
  25219. if (onError === void 0) { onError = null; }
  25220. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25221. if (name.substr(0, 5) !== "data:") {
  25222. name = "data:" + name;
  25223. }
  25224. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25225. };
  25226. // Constants
  25227. Texture.NEAREST_SAMPLINGMODE = 1;
  25228. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25229. Texture.BILINEAR_SAMPLINGMODE = 2;
  25230. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25231. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25232. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25233. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25234. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25235. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25236. Texture.NEAREST_LINEAR = 7;
  25237. Texture.NEAREST_NEAREST = 8;
  25238. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25239. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25240. Texture.LINEAR_LINEAR = 11;
  25241. Texture.LINEAR_NEAREST = 12;
  25242. Texture.EXPLICIT_MODE = 0;
  25243. Texture.SPHERICAL_MODE = 1;
  25244. Texture.PLANAR_MODE = 2;
  25245. Texture.CUBIC_MODE = 3;
  25246. Texture.PROJECTION_MODE = 4;
  25247. Texture.SKYBOX_MODE = 5;
  25248. Texture.INVCUBIC_MODE = 6;
  25249. Texture.EQUIRECTANGULAR_MODE = 7;
  25250. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25251. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25252. Texture.CLAMP_ADDRESSMODE = 0;
  25253. Texture.WRAP_ADDRESSMODE = 1;
  25254. Texture.MIRROR_ADDRESSMODE = 2;
  25255. __decorate([
  25256. BABYLON.serialize()
  25257. ], Texture.prototype, "url", void 0);
  25258. __decorate([
  25259. BABYLON.serialize()
  25260. ], Texture.prototype, "uOffset", void 0);
  25261. __decorate([
  25262. BABYLON.serialize()
  25263. ], Texture.prototype, "vOffset", void 0);
  25264. __decorate([
  25265. BABYLON.serialize()
  25266. ], Texture.prototype, "uScale", void 0);
  25267. __decorate([
  25268. BABYLON.serialize()
  25269. ], Texture.prototype, "vScale", void 0);
  25270. __decorate([
  25271. BABYLON.serialize()
  25272. ], Texture.prototype, "uAng", void 0);
  25273. __decorate([
  25274. BABYLON.serialize()
  25275. ], Texture.prototype, "vAng", void 0);
  25276. __decorate([
  25277. BABYLON.serialize()
  25278. ], Texture.prototype, "wAng", void 0);
  25279. __decorate([
  25280. BABYLON.serialize()
  25281. ], Texture.prototype, "isBlocking", null);
  25282. return Texture;
  25283. }(BABYLON.BaseTexture));
  25284. BABYLON.Texture = Texture;
  25285. })(BABYLON || (BABYLON = {}));
  25286. //# sourceMappingURL=babylon.texture.js.map
  25287. var BABYLON;
  25288. (function (BABYLON) {
  25289. var _InstancesBatch = /** @class */ (function () {
  25290. function _InstancesBatch() {
  25291. this.mustReturn = false;
  25292. this.visibleInstances = new Array();
  25293. this.renderSelf = new Array();
  25294. }
  25295. return _InstancesBatch;
  25296. }());
  25297. BABYLON._InstancesBatch = _InstancesBatch;
  25298. var Mesh = /** @class */ (function (_super) {
  25299. __extends(Mesh, _super);
  25300. /**
  25301. * @constructor
  25302. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25303. * @param {Scene} scene The scene to add this mesh to.
  25304. * @param {Node} parent The parent of this mesh, if it has one
  25305. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25306. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25307. * When false, achieved by calling a clone(), also passing False.
  25308. * This will make creation of children, recursive.
  25309. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25310. */
  25311. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25312. if (scene === void 0) { scene = null; }
  25313. if (parent === void 0) { parent = null; }
  25314. if (source === void 0) { source = null; }
  25315. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25316. var _this = _super.call(this, name, scene) || this;
  25317. // Events
  25318. /**
  25319. * An event triggered before rendering the mesh
  25320. * @type {BABYLON.Observable}
  25321. */
  25322. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25323. /**
  25324. * An event triggered after rendering the mesh
  25325. * @type {BABYLON.Observable}
  25326. */
  25327. _this.onAfterRenderObservable = new BABYLON.Observable();
  25328. /**
  25329. * An event triggered before drawing the mesh
  25330. * @type {BABYLON.Observable}
  25331. */
  25332. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25333. // Members
  25334. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25335. _this.instances = new Array();
  25336. _this._LODLevels = new Array();
  25337. _this._visibleInstances = {};
  25338. _this._renderIdForInstances = new Array();
  25339. _this._batchCache = new _InstancesBatch();
  25340. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25341. // Use by builder only to know what orientation were the mesh build in.
  25342. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25343. _this.overrideMaterialSideOrientation = null;
  25344. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25345. // Will be used to save a source mesh reference, If any
  25346. _this._source = null;
  25347. scene = _this.getScene();
  25348. if (source) {
  25349. // Source mesh
  25350. _this._source = source;
  25351. // Geometry
  25352. if (source._geometry) {
  25353. source._geometry.applyToMesh(_this);
  25354. }
  25355. // Deep copy
  25356. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25357. // Metadata
  25358. if (source.metadata && source.metadata.clone) {
  25359. _this.metadata = source.metadata.clone();
  25360. }
  25361. else {
  25362. _this.metadata = source.metadata;
  25363. }
  25364. // Tags
  25365. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25366. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25367. }
  25368. // Parent
  25369. _this.parent = source.parent;
  25370. // Pivot
  25371. _this.setPivotMatrix(source.getPivotMatrix());
  25372. _this.id = name + "." + source.id;
  25373. // Material
  25374. _this.material = source.material;
  25375. var index;
  25376. if (!doNotCloneChildren) {
  25377. // Children
  25378. var directDescendants = source.getDescendants(true);
  25379. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25380. var child = directDescendants[index_1];
  25381. if (child.clone) {
  25382. child.clone(name + "." + child.name, _this);
  25383. }
  25384. }
  25385. }
  25386. // Physics clone
  25387. var physicsEngine = _this.getScene().getPhysicsEngine();
  25388. if (clonePhysicsImpostor && physicsEngine) {
  25389. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25390. if (impostor) {
  25391. _this.physicsImpostor = impostor.clone(_this);
  25392. }
  25393. }
  25394. // Particles
  25395. for (index = 0; index < scene.particleSystems.length; index++) {
  25396. var system = scene.particleSystems[index];
  25397. if (system.emitter === source) {
  25398. system.clone(system.name, _this);
  25399. }
  25400. }
  25401. _this.computeWorldMatrix(true);
  25402. }
  25403. // Parent
  25404. if (parent !== null) {
  25405. _this.parent = parent;
  25406. }
  25407. return _this;
  25408. }
  25409. Object.defineProperty(Mesh, "FRONTSIDE", {
  25410. /**
  25411. * Mesh side orientation : usually the external or front surface
  25412. */
  25413. get: function () {
  25414. return Mesh._FRONTSIDE;
  25415. },
  25416. enumerable: true,
  25417. configurable: true
  25418. });
  25419. Object.defineProperty(Mesh, "BACKSIDE", {
  25420. /**
  25421. * Mesh side orientation : usually the internal or back surface
  25422. */
  25423. get: function () {
  25424. return Mesh._BACKSIDE;
  25425. },
  25426. enumerable: true,
  25427. configurable: true
  25428. });
  25429. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25430. /**
  25431. * Mesh side orientation : both internal and external or front and back surfaces
  25432. */
  25433. get: function () {
  25434. return Mesh._DOUBLESIDE;
  25435. },
  25436. enumerable: true,
  25437. configurable: true
  25438. });
  25439. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25440. /**
  25441. * Mesh side orientation : by default, `FRONTSIDE`
  25442. */
  25443. get: function () {
  25444. return Mesh._DEFAULTSIDE;
  25445. },
  25446. enumerable: true,
  25447. configurable: true
  25448. });
  25449. Object.defineProperty(Mesh, "NO_CAP", {
  25450. /**
  25451. * Mesh cap setting : no cap
  25452. */
  25453. get: function () {
  25454. return Mesh._NO_CAP;
  25455. },
  25456. enumerable: true,
  25457. configurable: true
  25458. });
  25459. Object.defineProperty(Mesh, "CAP_START", {
  25460. /**
  25461. * Mesh cap setting : one cap at the beginning of the mesh
  25462. */
  25463. get: function () {
  25464. return Mesh._CAP_START;
  25465. },
  25466. enumerable: true,
  25467. configurable: true
  25468. });
  25469. Object.defineProperty(Mesh, "CAP_END", {
  25470. /**
  25471. * Mesh cap setting : one cap at the end of the mesh
  25472. */
  25473. get: function () {
  25474. return Mesh._CAP_END;
  25475. },
  25476. enumerable: true,
  25477. configurable: true
  25478. });
  25479. Object.defineProperty(Mesh, "CAP_ALL", {
  25480. /**
  25481. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25482. */
  25483. get: function () {
  25484. return Mesh._CAP_ALL;
  25485. },
  25486. enumerable: true,
  25487. configurable: true
  25488. });
  25489. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25490. set: function (callback) {
  25491. if (this._onBeforeDrawObserver) {
  25492. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25493. }
  25494. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25495. },
  25496. enumerable: true,
  25497. configurable: true
  25498. });
  25499. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25500. get: function () {
  25501. return this._morphTargetManager;
  25502. },
  25503. set: function (value) {
  25504. if (this._morphTargetManager === value) {
  25505. return;
  25506. }
  25507. this._morphTargetManager = value;
  25508. this._syncGeometryWithMorphTargetManager();
  25509. },
  25510. enumerable: true,
  25511. configurable: true
  25512. });
  25513. Object.defineProperty(Mesh.prototype, "source", {
  25514. get: function () {
  25515. return this._source;
  25516. },
  25517. enumerable: true,
  25518. configurable: true
  25519. });
  25520. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25521. get: function () {
  25522. return this._unIndexed;
  25523. },
  25524. set: function (value) {
  25525. if (this._unIndexed !== value) {
  25526. this._unIndexed = value;
  25527. this._markSubMeshesAsAttributesDirty();
  25528. }
  25529. },
  25530. enumerable: true,
  25531. configurable: true
  25532. });
  25533. // Methods
  25534. /**
  25535. * Returns the string "Mesh".
  25536. */
  25537. Mesh.prototype.getClassName = function () {
  25538. return "Mesh";
  25539. };
  25540. /**
  25541. * Returns a string.
  25542. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25543. */
  25544. Mesh.prototype.toString = function (fullDetails) {
  25545. var ret = _super.prototype.toString.call(this, fullDetails);
  25546. ret += ", n vertices: " + this.getTotalVertices();
  25547. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25548. if (this.animations) {
  25549. for (var i = 0; i < this.animations.length; i++) {
  25550. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25551. }
  25552. }
  25553. if (fullDetails) {
  25554. if (this._geometry) {
  25555. var ib = this.getIndices();
  25556. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25557. if (vb && ib) {
  25558. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25559. }
  25560. }
  25561. else {
  25562. ret += ", flat shading: UNKNOWN";
  25563. }
  25564. }
  25565. return ret;
  25566. };
  25567. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25568. /**
  25569. * True if the mesh has some Levels Of Details (LOD).
  25570. * Returns a boolean.
  25571. */
  25572. get: function () {
  25573. return this._LODLevels.length > 0;
  25574. },
  25575. enumerable: true,
  25576. configurable: true
  25577. });
  25578. /**
  25579. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25580. * @returns an array of {BABYLON.MeshLODLevel}
  25581. */
  25582. Mesh.prototype.getLODLevels = function () {
  25583. return this._LODLevels;
  25584. };
  25585. Mesh.prototype._sortLODLevels = function () {
  25586. this._LODLevels.sort(function (a, b) {
  25587. if (a.distance < b.distance) {
  25588. return 1;
  25589. }
  25590. if (a.distance > b.distance) {
  25591. return -1;
  25592. }
  25593. return 0;
  25594. });
  25595. };
  25596. /**
  25597. * Add a mesh as LOD level triggered at the given distance.
  25598. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25599. * @param {number} distance The distance from the center of the object to show this level
  25600. * @param {Mesh} mesh The mesh to be added as LOD level
  25601. * @return {Mesh} This mesh (for chaining)
  25602. */
  25603. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25604. if (mesh && mesh._masterMesh) {
  25605. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25606. return this;
  25607. }
  25608. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25609. this._LODLevels.push(level);
  25610. if (mesh) {
  25611. mesh._masterMesh = this;
  25612. }
  25613. this._sortLODLevels();
  25614. return this;
  25615. };
  25616. /**
  25617. * Returns the LOD level mesh at the passed distance or null if not found.
  25618. * It is related to the method `addLODLevel(distance, mesh)`.
  25619. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25620. * Returns an object Mesh or `null`.
  25621. */
  25622. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25623. for (var index = 0; index < this._LODLevels.length; index++) {
  25624. var level = this._LODLevels[index];
  25625. if (level.distance === distance) {
  25626. return level.mesh;
  25627. }
  25628. }
  25629. return null;
  25630. };
  25631. /**
  25632. * Remove a mesh from the LOD array
  25633. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25634. * @param {Mesh} mesh The mesh to be removed.
  25635. * @return {Mesh} This mesh (for chaining)
  25636. */
  25637. Mesh.prototype.removeLODLevel = function (mesh) {
  25638. for (var index = 0; index < this._LODLevels.length; index++) {
  25639. if (this._LODLevels[index].mesh === mesh) {
  25640. this._LODLevels.splice(index, 1);
  25641. if (mesh) {
  25642. mesh._masterMesh = null;
  25643. }
  25644. }
  25645. }
  25646. this._sortLODLevels();
  25647. return this;
  25648. };
  25649. /**
  25650. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25651. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25652. */
  25653. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25654. if (!this._LODLevels || this._LODLevels.length === 0) {
  25655. return this;
  25656. }
  25657. var bSphere;
  25658. if (boundingSphere) {
  25659. bSphere = boundingSphere;
  25660. }
  25661. else {
  25662. var boundingInfo = this.getBoundingInfo();
  25663. bSphere = boundingInfo.boundingSphere;
  25664. }
  25665. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25666. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25667. if (this.onLODLevelSelection) {
  25668. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25669. }
  25670. return this;
  25671. }
  25672. for (var index = 0; index < this._LODLevels.length; index++) {
  25673. var level = this._LODLevels[index];
  25674. if (level.distance < distanceToCamera) {
  25675. if (level.mesh) {
  25676. level.mesh._preActivate();
  25677. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25678. }
  25679. if (this.onLODLevelSelection) {
  25680. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25681. }
  25682. return level.mesh;
  25683. }
  25684. }
  25685. if (this.onLODLevelSelection) {
  25686. this.onLODLevelSelection(distanceToCamera, this, this);
  25687. }
  25688. return this;
  25689. };
  25690. Object.defineProperty(Mesh.prototype, "geometry", {
  25691. /**
  25692. * Returns the mesh internal Geometry object.
  25693. */
  25694. get: function () {
  25695. return this._geometry;
  25696. },
  25697. enumerable: true,
  25698. configurable: true
  25699. });
  25700. /**
  25701. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25702. */
  25703. Mesh.prototype.getTotalVertices = function () {
  25704. if (this._geometry === null || this._geometry === undefined) {
  25705. return 0;
  25706. }
  25707. return this._geometry.getTotalVertices();
  25708. };
  25709. /**
  25710. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25711. * 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.
  25712. * You can force the copy with forceCopy === true
  25713. * Returns null if the mesh has no geometry or no vertex buffer.
  25714. * Possible `kind` values :
  25715. * - BABYLON.VertexBuffer.PositionKind
  25716. * - BABYLON.VertexBuffer.UVKind
  25717. * - BABYLON.VertexBuffer.UV2Kind
  25718. * - BABYLON.VertexBuffer.UV3Kind
  25719. * - BABYLON.VertexBuffer.UV4Kind
  25720. * - BABYLON.VertexBuffer.UV5Kind
  25721. * - BABYLON.VertexBuffer.UV6Kind
  25722. * - BABYLON.VertexBuffer.ColorKind
  25723. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25724. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25725. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25726. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25727. */
  25728. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25729. if (!this._geometry) {
  25730. return null;
  25731. }
  25732. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25733. };
  25734. /**
  25735. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25736. * Returns `null` if the mesh has no geometry.
  25737. * Possible `kind` values :
  25738. * - BABYLON.VertexBuffer.PositionKind
  25739. * - BABYLON.VertexBuffer.UVKind
  25740. * - BABYLON.VertexBuffer.UV2Kind
  25741. * - BABYLON.VertexBuffer.UV3Kind
  25742. * - BABYLON.VertexBuffer.UV4Kind
  25743. * - BABYLON.VertexBuffer.UV5Kind
  25744. * - BABYLON.VertexBuffer.UV6Kind
  25745. * - BABYLON.VertexBuffer.ColorKind
  25746. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25747. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25748. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25749. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25750. */
  25751. Mesh.prototype.getVertexBuffer = function (kind) {
  25752. if (!this._geometry) {
  25753. return null;
  25754. }
  25755. return this._geometry.getVertexBuffer(kind);
  25756. };
  25757. /**
  25758. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25759. * Possible `kind` values :
  25760. * - BABYLON.VertexBuffer.PositionKind
  25761. * - BABYLON.VertexBuffer.UVKind
  25762. * - BABYLON.VertexBuffer.UV2Kind
  25763. * - BABYLON.VertexBuffer.UV3Kind
  25764. * - BABYLON.VertexBuffer.UV4Kind
  25765. * - BABYLON.VertexBuffer.UV5Kind
  25766. * - BABYLON.VertexBuffer.UV6Kind
  25767. * - BABYLON.VertexBuffer.ColorKind
  25768. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25769. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25770. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25771. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25772. */
  25773. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25774. if (!this._geometry) {
  25775. if (this._delayInfo) {
  25776. return this._delayInfo.indexOf(kind) !== -1;
  25777. }
  25778. return false;
  25779. }
  25780. return this._geometry.isVerticesDataPresent(kind);
  25781. };
  25782. /**
  25783. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25784. * Possible `kind` values :
  25785. * - BABYLON.VertexBuffer.PositionKind
  25786. * - BABYLON.VertexBuffer.UVKind
  25787. * - BABYLON.VertexBuffer.UV2Kind
  25788. * - BABYLON.VertexBuffer.UV3Kind
  25789. * - BABYLON.VertexBuffer.UV4Kind
  25790. * - BABYLON.VertexBuffer.UV5Kind
  25791. * - BABYLON.VertexBuffer.UV6Kind
  25792. * - BABYLON.VertexBuffer.ColorKind
  25793. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25794. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25795. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25796. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25797. */
  25798. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25799. if (!this._geometry) {
  25800. if (this._delayInfo) {
  25801. return this._delayInfo.indexOf(kind) !== -1;
  25802. }
  25803. return false;
  25804. }
  25805. return this._geometry.isVertexBufferUpdatable(kind);
  25806. };
  25807. /**
  25808. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25809. * Possible `kind` values :
  25810. * - BABYLON.VertexBuffer.PositionKind
  25811. * - BABYLON.VertexBuffer.UVKind
  25812. * - BABYLON.VertexBuffer.UV2Kind
  25813. * - BABYLON.VertexBuffer.UV3Kind
  25814. * - BABYLON.VertexBuffer.UV4Kind
  25815. * - BABYLON.VertexBuffer.UV5Kind
  25816. * - BABYLON.VertexBuffer.UV6Kind
  25817. * - BABYLON.VertexBuffer.ColorKind
  25818. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25819. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25820. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25821. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25822. */
  25823. Mesh.prototype.getVerticesDataKinds = function () {
  25824. if (!this._geometry) {
  25825. var result = new Array();
  25826. if (this._delayInfo) {
  25827. this._delayInfo.forEach(function (kind, index, array) {
  25828. result.push(kind);
  25829. });
  25830. }
  25831. return result;
  25832. }
  25833. return this._geometry.getVerticesDataKinds();
  25834. };
  25835. /**
  25836. * Returns a positive integer : the total number of indices in this mesh geometry.
  25837. * Returns zero if the mesh has no geometry.
  25838. */
  25839. Mesh.prototype.getTotalIndices = function () {
  25840. if (!this._geometry) {
  25841. return 0;
  25842. }
  25843. return this._geometry.getTotalIndices();
  25844. };
  25845. /**
  25846. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25847. * 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.
  25848. * Returns an empty array if the mesh has no geometry.
  25849. */
  25850. Mesh.prototype.getIndices = function (copyWhenShared) {
  25851. if (!this._geometry) {
  25852. return [];
  25853. }
  25854. return this._geometry.getIndices(copyWhenShared);
  25855. };
  25856. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25857. get: function () {
  25858. return this._masterMesh !== null && this._masterMesh !== undefined;
  25859. },
  25860. enumerable: true,
  25861. configurable: true
  25862. });
  25863. /**
  25864. * Determine if the current mesh is ready to be rendered
  25865. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25866. * @returns true if all associated assets are ready (material, textures, shaders)
  25867. */
  25868. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25869. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25870. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25871. return false;
  25872. }
  25873. if (!_super.prototype.isReady.call(this)) {
  25874. return false;
  25875. }
  25876. if (!this.subMeshes || this.subMeshes.length === 0) {
  25877. return true;
  25878. }
  25879. var engine = this.getEngine();
  25880. var scene = this.getScene();
  25881. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25882. this.computeWorldMatrix();
  25883. var mat = this.material || scene.defaultMaterial;
  25884. if (mat) {
  25885. if (mat.storeEffectOnSubMeshes) {
  25886. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25887. var subMesh = _a[_i];
  25888. var effectiveMaterial = subMesh.getMaterial();
  25889. if (effectiveMaterial) {
  25890. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25891. return false;
  25892. }
  25893. }
  25894. }
  25895. }
  25896. else {
  25897. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25898. return false;
  25899. }
  25900. }
  25901. }
  25902. // Shadows
  25903. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25904. var light = _c[_b];
  25905. var generator = light.getShadowGenerator();
  25906. if (generator) {
  25907. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25908. var subMesh = _e[_d];
  25909. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25910. return false;
  25911. }
  25912. }
  25913. }
  25914. }
  25915. // LOD
  25916. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25917. var lod = _g[_f];
  25918. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25919. return false;
  25920. }
  25921. }
  25922. return true;
  25923. };
  25924. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25925. /**
  25926. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25927. * This property is pertinent only for updatable parametric shapes.
  25928. */
  25929. get: function () {
  25930. return this._areNormalsFrozen;
  25931. },
  25932. enumerable: true,
  25933. configurable: true
  25934. });
  25935. /**
  25936. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25937. * It has no effect at all on other shapes.
  25938. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25939. * Returns the Mesh.
  25940. */
  25941. Mesh.prototype.freezeNormals = function () {
  25942. this._areNormalsFrozen = true;
  25943. return this;
  25944. };
  25945. /**
  25946. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25947. * It has no effect at all on other shapes.
  25948. * It reactivates the mesh normals computation if it was previously frozen.
  25949. * Returns the Mesh.
  25950. */
  25951. Mesh.prototype.unfreezeNormals = function () {
  25952. this._areNormalsFrozen = false;
  25953. return this;
  25954. };
  25955. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25956. /**
  25957. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25958. */
  25959. set: function (count) {
  25960. this._overridenInstanceCount = count;
  25961. },
  25962. enumerable: true,
  25963. configurable: true
  25964. });
  25965. // Methods
  25966. Mesh.prototype._preActivate = function () {
  25967. var sceneRenderId = this.getScene().getRenderId();
  25968. if (this._preActivateId === sceneRenderId) {
  25969. return this;
  25970. }
  25971. this._preActivateId = sceneRenderId;
  25972. this._visibleInstances = null;
  25973. return this;
  25974. };
  25975. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25976. if (this._visibleInstances) {
  25977. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25978. }
  25979. return this;
  25980. };
  25981. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25982. if (!this._visibleInstances) {
  25983. this._visibleInstances = {};
  25984. this._visibleInstances.defaultRenderId = renderId;
  25985. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25986. }
  25987. if (!this._visibleInstances[renderId]) {
  25988. this._visibleInstances[renderId] = new Array();
  25989. }
  25990. this._visibleInstances[renderId].push(instance);
  25991. return this;
  25992. };
  25993. /**
  25994. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25995. * This means the mesh underlying bounding box and sphere are recomputed.
  25996. * Returns the Mesh.
  25997. */
  25998. Mesh.prototype.refreshBoundingInfo = function () {
  25999. return this._refreshBoundingInfo(false);
  26000. };
  26001. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26002. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26003. return this;
  26004. }
  26005. var data = this._getPositionData(applySkeleton);
  26006. if (data) {
  26007. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26008. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26009. }
  26010. if (this.subMeshes) {
  26011. for (var index = 0; index < this.subMeshes.length; index++) {
  26012. this.subMeshes[index].refreshBoundingInfo();
  26013. }
  26014. }
  26015. this._updateBoundingInfo();
  26016. return this;
  26017. };
  26018. Mesh.prototype._getPositionData = function (applySkeleton) {
  26019. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26020. if (data && applySkeleton && this.skeleton) {
  26021. data = BABYLON.Tools.Slice(data);
  26022. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26023. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26024. if (matricesWeightsData && matricesIndicesData) {
  26025. var needExtras = this.numBoneInfluencers > 4;
  26026. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26027. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26028. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26029. var tempVector = BABYLON.Tmp.Vector3[0];
  26030. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26031. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26032. var matWeightIdx = 0;
  26033. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26034. finalMatrix.reset();
  26035. var inf;
  26036. var weight;
  26037. for (inf = 0; inf < 4; inf++) {
  26038. weight = matricesWeightsData[matWeightIdx + inf];
  26039. if (weight <= 0)
  26040. break;
  26041. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26042. finalMatrix.addToSelf(tempMatrix);
  26043. }
  26044. if (needExtras) {
  26045. for (inf = 0; inf < 4; inf++) {
  26046. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26047. if (weight <= 0)
  26048. break;
  26049. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26050. finalMatrix.addToSelf(tempMatrix);
  26051. }
  26052. }
  26053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26054. tempVector.toArray(data, index);
  26055. }
  26056. }
  26057. }
  26058. return data;
  26059. };
  26060. Mesh.prototype._createGlobalSubMesh = function (force) {
  26061. var totalVertices = this.getTotalVertices();
  26062. if (!totalVertices || !this.getIndices()) {
  26063. return null;
  26064. }
  26065. // Check if we need to recreate the submeshes
  26066. if (this.subMeshes && this.subMeshes.length > 0) {
  26067. var ib = this.getIndices();
  26068. if (!ib) {
  26069. return null;
  26070. }
  26071. var totalIndices = ib.length;
  26072. var needToRecreate = false;
  26073. if (force) {
  26074. needToRecreate = true;
  26075. }
  26076. else {
  26077. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26078. var submesh = _a[_i];
  26079. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26080. needToRecreate = true;
  26081. break;
  26082. }
  26083. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26084. needToRecreate = true;
  26085. break;
  26086. }
  26087. }
  26088. }
  26089. if (!needToRecreate) {
  26090. return this.subMeshes[0];
  26091. }
  26092. }
  26093. this.releaseSubMeshes();
  26094. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26095. };
  26096. Mesh.prototype.subdivide = function (count) {
  26097. if (count < 1) {
  26098. return;
  26099. }
  26100. var totalIndices = this.getTotalIndices();
  26101. var subdivisionSize = (totalIndices / count) | 0;
  26102. var offset = 0;
  26103. // Ensure that subdivisionSize is a multiple of 3
  26104. while (subdivisionSize % 3 !== 0) {
  26105. subdivisionSize++;
  26106. }
  26107. this.releaseSubMeshes();
  26108. for (var index = 0; index < count; index++) {
  26109. if (offset >= totalIndices) {
  26110. break;
  26111. }
  26112. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26113. offset += subdivisionSize;
  26114. }
  26115. this.synchronizeInstances();
  26116. };
  26117. /**
  26118. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26119. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26120. * The `data` are either a numeric array either a Float32Array.
  26121. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26122. * 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).
  26123. * Note that a new underlying VertexBuffer object is created each call.
  26124. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26125. *
  26126. * Possible `kind` values :
  26127. * - BABYLON.VertexBuffer.PositionKind
  26128. * - BABYLON.VertexBuffer.UVKind
  26129. * - BABYLON.VertexBuffer.UV2Kind
  26130. * - BABYLON.VertexBuffer.UV3Kind
  26131. * - BABYLON.VertexBuffer.UV4Kind
  26132. * - BABYLON.VertexBuffer.UV5Kind
  26133. * - BABYLON.VertexBuffer.UV6Kind
  26134. * - BABYLON.VertexBuffer.ColorKind
  26135. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26136. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26137. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26138. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26139. *
  26140. * Returns the Mesh.
  26141. */
  26142. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26143. if (updatable === void 0) { updatable = false; }
  26144. if (!this._geometry) {
  26145. var vertexData = new BABYLON.VertexData();
  26146. vertexData.set(data, kind);
  26147. var scene = this.getScene();
  26148. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26149. }
  26150. else {
  26151. this._geometry.setVerticesData(kind, data, updatable, stride);
  26152. }
  26153. return this;
  26154. };
  26155. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26156. if (updatable === void 0) { updatable = true; }
  26157. var vb = this.getVertexBuffer(kind);
  26158. if (!vb || vb.isUpdatable() === updatable) {
  26159. return;
  26160. }
  26161. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26162. };
  26163. /**
  26164. * Sets the mesh VertexBuffer.
  26165. * Returns the Mesh.
  26166. */
  26167. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26168. if (!this._geometry) {
  26169. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26170. }
  26171. this._geometry.setVerticesBuffer(buffer);
  26172. return this;
  26173. };
  26174. /**
  26175. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26176. * If the mesh has no geometry, it is simply returned as it is.
  26177. * The `data` are either a numeric array either a Float32Array.
  26178. * No new underlying VertexBuffer object is created.
  26179. * 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.
  26180. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26181. *
  26182. * Possible `kind` values :
  26183. * - BABYLON.VertexBuffer.PositionKind
  26184. * - BABYLON.VertexBuffer.UVKind
  26185. * - BABYLON.VertexBuffer.UV2Kind
  26186. * - BABYLON.VertexBuffer.UV3Kind
  26187. * - BABYLON.VertexBuffer.UV4Kind
  26188. * - BABYLON.VertexBuffer.UV5Kind
  26189. * - BABYLON.VertexBuffer.UV6Kind
  26190. * - BABYLON.VertexBuffer.ColorKind
  26191. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26192. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26193. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26194. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26195. *
  26196. * Returns the Mesh.
  26197. */
  26198. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26199. if (!this._geometry) {
  26200. return this;
  26201. }
  26202. if (!makeItUnique) {
  26203. this._geometry.updateVerticesData(kind, data, updateExtends);
  26204. }
  26205. else {
  26206. this.makeGeometryUnique();
  26207. this.updateVerticesData(kind, data, updateExtends, false);
  26208. }
  26209. return this;
  26210. };
  26211. /**
  26212. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26213. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26214. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26215. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26216. * Returns the Mesh.
  26217. */
  26218. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26219. if (computeNormals === void 0) { computeNormals = true; }
  26220. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26221. if (!positions) {
  26222. return this;
  26223. }
  26224. positionFunction(positions);
  26225. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26226. if (computeNormals) {
  26227. var indices = this.getIndices();
  26228. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26229. if (!normals) {
  26230. return this;
  26231. }
  26232. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26233. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26234. }
  26235. return this;
  26236. };
  26237. /**
  26238. * Creates a un-shared specific occurence of the geometry for the mesh.
  26239. * Returns the Mesh.
  26240. */
  26241. Mesh.prototype.makeGeometryUnique = function () {
  26242. if (!this._geometry) {
  26243. return this;
  26244. }
  26245. var oldGeometry = this._geometry;
  26246. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26247. oldGeometry.releaseForMesh(this, true);
  26248. geometry.applyToMesh(this);
  26249. return this;
  26250. };
  26251. /**
  26252. * Sets the mesh indices.
  26253. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26254. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26255. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26256. * This method creates a new index buffer each call.
  26257. * Returns the Mesh.
  26258. */
  26259. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26260. if (totalVertices === void 0) { totalVertices = null; }
  26261. if (updatable === void 0) { updatable = false; }
  26262. if (!this._geometry) {
  26263. var vertexData = new BABYLON.VertexData();
  26264. vertexData.indices = indices;
  26265. var scene = this.getScene();
  26266. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26267. }
  26268. else {
  26269. this._geometry.setIndices(indices, totalVertices, updatable);
  26270. }
  26271. return this;
  26272. };
  26273. /**
  26274. * Update the current index buffer
  26275. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26276. * Returns the Mesh.
  26277. */
  26278. Mesh.prototype.updateIndices = function (indices, offset) {
  26279. if (!this._geometry) {
  26280. return this;
  26281. }
  26282. this._geometry.updateIndices(indices, offset);
  26283. return this;
  26284. };
  26285. /**
  26286. * Invert the geometry to move from a right handed system to a left handed one.
  26287. * Returns the Mesh.
  26288. */
  26289. Mesh.prototype.toLeftHanded = function () {
  26290. if (!this._geometry) {
  26291. return this;
  26292. }
  26293. this._geometry.toLeftHanded();
  26294. return this;
  26295. };
  26296. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26297. if (!this._geometry) {
  26298. return this;
  26299. }
  26300. var engine = this.getScene().getEngine();
  26301. // Wireframe
  26302. var indexToBind;
  26303. if (this._unIndexed) {
  26304. indexToBind = null;
  26305. }
  26306. else {
  26307. switch (fillMode) {
  26308. case BABYLON.Material.PointFillMode:
  26309. indexToBind = null;
  26310. break;
  26311. case BABYLON.Material.WireFrameFillMode:
  26312. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26313. break;
  26314. default:
  26315. case BABYLON.Material.TriangleFillMode:
  26316. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26317. break;
  26318. }
  26319. }
  26320. // VBOs
  26321. this._geometry._bind(effect, indexToBind);
  26322. return this;
  26323. };
  26324. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26325. if (alternate === void 0) { alternate = false; }
  26326. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26327. return this;
  26328. }
  26329. this.onBeforeDrawObservable.notifyObservers(this);
  26330. var scene = this.getScene();
  26331. var engine = scene.getEngine();
  26332. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26333. // or triangles as points
  26334. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26335. }
  26336. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26337. // Triangles as wireframe
  26338. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26339. }
  26340. else {
  26341. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26342. }
  26343. if (scene._isAlternateRenderingEnabled && !alternate) {
  26344. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26345. if (!effect || !scene.activeCamera) {
  26346. return this;
  26347. }
  26348. scene._switchToAlternateCameraConfiguration(true);
  26349. this._effectiveMaterial.bindView(effect);
  26350. this._effectiveMaterial.bindViewProjection(effect);
  26351. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26352. this._draw(subMesh, fillMode, instancesCount, true);
  26353. engine.setViewport(scene.activeCamera.viewport);
  26354. scene._switchToAlternateCameraConfiguration(false);
  26355. this._effectiveMaterial.bindView(effect);
  26356. this._effectiveMaterial.bindViewProjection(effect);
  26357. }
  26358. return this;
  26359. };
  26360. /**
  26361. * Registers for this mesh a javascript function called just before the rendering process.
  26362. * This function is passed the current mesh.
  26363. * Return the Mesh.
  26364. */
  26365. Mesh.prototype.registerBeforeRender = function (func) {
  26366. this.onBeforeRenderObservable.add(func);
  26367. return this;
  26368. };
  26369. /**
  26370. * Disposes a previously registered javascript function called before the rendering.
  26371. * This function is passed the current mesh.
  26372. * Returns the Mesh.
  26373. */
  26374. Mesh.prototype.unregisterBeforeRender = function (func) {
  26375. this.onBeforeRenderObservable.removeCallback(func);
  26376. return this;
  26377. };
  26378. /**
  26379. * Registers for this mesh a javascript function called just after the rendering is complete.
  26380. * This function is passed the current mesh.
  26381. * Returns the Mesh.
  26382. */
  26383. Mesh.prototype.registerAfterRender = function (func) {
  26384. this.onAfterRenderObservable.add(func);
  26385. return this;
  26386. };
  26387. /**
  26388. * Disposes a previously registered javascript function called after the rendering.
  26389. * This function is passed the current mesh.
  26390. * Return the Mesh.
  26391. */
  26392. Mesh.prototype.unregisterAfterRender = function (func) {
  26393. this.onAfterRenderObservable.removeCallback(func);
  26394. return this;
  26395. };
  26396. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26397. var scene = this.getScene();
  26398. this._batchCache.mustReturn = false;
  26399. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26400. this._batchCache.visibleInstances[subMeshId] = null;
  26401. if (this._visibleInstances) {
  26402. var currentRenderId = scene.getRenderId();
  26403. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26404. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26405. var selfRenderId = this._renderId;
  26406. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26407. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26408. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26409. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26410. }
  26411. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26412. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26413. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26414. this._batchCache.mustReturn = true;
  26415. return this._batchCache;
  26416. }
  26417. if (currentRenderId !== selfRenderId) {
  26418. this._batchCache.renderSelf[subMeshId] = false;
  26419. }
  26420. }
  26421. this._renderIdForInstances[subMeshId] = currentRenderId;
  26422. }
  26423. return this._batchCache;
  26424. };
  26425. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26426. var visibleInstances = batch.visibleInstances[subMesh._id];
  26427. if (!visibleInstances) {
  26428. return this;
  26429. }
  26430. var matricesCount = visibleInstances.length + 1;
  26431. var bufferSize = matricesCount * 16 * 4;
  26432. var currentInstancesBufferSize = this._instancesBufferSize;
  26433. var instancesBuffer = this._instancesBuffer;
  26434. while (this._instancesBufferSize < bufferSize) {
  26435. this._instancesBufferSize *= 2;
  26436. }
  26437. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26438. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26439. }
  26440. var offset = 0;
  26441. var instancesCount = 0;
  26442. var world = this.getWorldMatrix();
  26443. if (batch.renderSelf[subMesh._id]) {
  26444. world.copyToArray(this._instancesData, offset);
  26445. offset += 16;
  26446. instancesCount++;
  26447. }
  26448. if (visibleInstances) {
  26449. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26450. var instance = visibleInstances[instanceIndex];
  26451. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26452. offset += 16;
  26453. instancesCount++;
  26454. }
  26455. }
  26456. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26457. if (instancesBuffer) {
  26458. instancesBuffer.dispose();
  26459. }
  26460. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26461. this._instancesBuffer = instancesBuffer;
  26462. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26463. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26464. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26465. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26466. }
  26467. else {
  26468. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26469. }
  26470. this._bind(subMesh, effect, fillMode);
  26471. this._draw(subMesh, fillMode, instancesCount);
  26472. engine.unbindInstanceAttributes();
  26473. return this;
  26474. };
  26475. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26476. var scene = this.getScene();
  26477. var engine = scene.getEngine();
  26478. if (hardwareInstancedRendering) {
  26479. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26480. }
  26481. else {
  26482. if (batch.renderSelf[subMesh._id]) {
  26483. // Draw
  26484. if (onBeforeDraw) {
  26485. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26486. }
  26487. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26488. }
  26489. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26490. if (visibleInstancesForSubMesh) {
  26491. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26492. var instance = visibleInstancesForSubMesh[instanceIndex];
  26493. // World
  26494. var world = instance.getWorldMatrix();
  26495. if (onBeforeDraw) {
  26496. onBeforeDraw(true, world, effectiveMaterial);
  26497. }
  26498. // Draw
  26499. this._draw(subMesh, fillMode);
  26500. }
  26501. }
  26502. }
  26503. return this;
  26504. };
  26505. /**
  26506. * Triggers the draw call for the mesh.
  26507. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26508. * Returns the Mesh.
  26509. */
  26510. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26511. this.checkOcclusionQuery();
  26512. if (this._isOccluded) {
  26513. return this;
  26514. }
  26515. var scene = this.getScene();
  26516. // Managing instances
  26517. var batch = this._getInstancesRenderList(subMesh._id);
  26518. if (batch.mustReturn) {
  26519. return this;
  26520. }
  26521. // Checking geometry state
  26522. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26523. return this;
  26524. }
  26525. this.onBeforeRenderObservable.notifyObservers(this);
  26526. var engine = scene.getEngine();
  26527. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26528. // Material
  26529. var material = subMesh.getMaterial();
  26530. if (!material) {
  26531. return this;
  26532. }
  26533. this._effectiveMaterial = material;
  26534. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26535. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26536. return this;
  26537. }
  26538. }
  26539. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26540. return this;
  26541. }
  26542. // Alpha mode
  26543. if (enableAlphaMode) {
  26544. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26545. }
  26546. // Outline - step 1
  26547. var savedDepthWrite = engine.getDepthWrite();
  26548. if (this.renderOutline) {
  26549. engine.setDepthWrite(false);
  26550. scene.getOutlineRenderer().render(subMesh, batch);
  26551. engine.setDepthWrite(savedDepthWrite);
  26552. }
  26553. var effect;
  26554. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26555. effect = subMesh.effect;
  26556. }
  26557. else {
  26558. effect = this._effectiveMaterial.getEffect();
  26559. }
  26560. if (!effect) {
  26561. return this;
  26562. }
  26563. var sideOrientation = this.overrideMaterialSideOrientation;
  26564. if (sideOrientation == null) {
  26565. sideOrientation = this._effectiveMaterial.sideOrientation;
  26566. if (this._getWorldMatrixDeterminant() < 0) {
  26567. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26568. }
  26569. }
  26570. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26571. if (this._effectiveMaterial.forceDepthWrite) {
  26572. engine.setDepthWrite(true);
  26573. }
  26574. // Bind
  26575. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26576. if (!hardwareInstancedRendering) {
  26577. this._bind(subMesh, effect, fillMode);
  26578. }
  26579. var world = this.getWorldMatrix();
  26580. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26581. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26582. }
  26583. else {
  26584. this._effectiveMaterial.bind(world, this);
  26585. }
  26586. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26587. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26588. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26589. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26590. }
  26591. // Draw
  26592. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26593. // Unbind
  26594. this._effectiveMaterial.unbind();
  26595. // Outline - step 2
  26596. if (this.renderOutline && savedDepthWrite) {
  26597. engine.setDepthWrite(true);
  26598. engine.setColorWrite(false);
  26599. scene.getOutlineRenderer().render(subMesh, batch);
  26600. engine.setColorWrite(true);
  26601. }
  26602. // Overlay
  26603. if (this.renderOverlay) {
  26604. var currentMode = engine.getAlphaMode();
  26605. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26606. scene.getOutlineRenderer().render(subMesh, batch, true);
  26607. engine.setAlphaMode(currentMode);
  26608. }
  26609. this.onAfterRenderObservable.notifyObservers(this);
  26610. return this;
  26611. };
  26612. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26613. if (isInstance && effectiveMaterial) {
  26614. effectiveMaterial.bindOnlyWorldMatrix(world);
  26615. }
  26616. };
  26617. /**
  26618. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26619. */
  26620. Mesh.prototype.getEmittedParticleSystems = function () {
  26621. var results = new Array();
  26622. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26623. var particleSystem = this.getScene().particleSystems[index];
  26624. if (particleSystem.emitter === this) {
  26625. results.push(particleSystem);
  26626. }
  26627. }
  26628. return results;
  26629. };
  26630. /**
  26631. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26632. */
  26633. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26634. var results = new Array();
  26635. var descendants = this.getDescendants();
  26636. descendants.push(this);
  26637. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26638. var particleSystem = this.getScene().particleSystems[index];
  26639. var emitter = particleSystem.emitter;
  26640. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26641. results.push(particleSystem);
  26642. }
  26643. }
  26644. return results;
  26645. };
  26646. Mesh.prototype._checkDelayState = function () {
  26647. var scene = this.getScene();
  26648. if (this._geometry) {
  26649. this._geometry.load(scene);
  26650. }
  26651. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26653. this._queueLoad(scene);
  26654. }
  26655. return this;
  26656. };
  26657. Mesh.prototype._queueLoad = function (scene) {
  26658. var _this = this;
  26659. scene._addPendingData(this);
  26660. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26661. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26662. if (data instanceof ArrayBuffer) {
  26663. _this._delayLoadingFunction(data, _this);
  26664. }
  26665. else {
  26666. _this._delayLoadingFunction(JSON.parse(data), _this);
  26667. }
  26668. _this.instances.forEach(function (instance) {
  26669. instance._syncSubMeshes();
  26670. });
  26671. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26672. scene._removePendingData(_this);
  26673. }, function () { }, scene.database, getBinaryData);
  26674. return this;
  26675. };
  26676. /**
  26677. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26678. */
  26679. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26680. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26681. return false;
  26682. }
  26683. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26684. return false;
  26685. }
  26686. this._checkDelayState();
  26687. return true;
  26688. };
  26689. /**
  26690. * Sets the mesh material by the material or multiMaterial `id` property.
  26691. * The material `id` is a string identifying the material or the multiMaterial.
  26692. * This method returns the Mesh.
  26693. */
  26694. Mesh.prototype.setMaterialByID = function (id) {
  26695. var materials = this.getScene().materials;
  26696. var index;
  26697. for (index = materials.length - 1; index > -1; index--) {
  26698. if (materials[index].id === id) {
  26699. this.material = materials[index];
  26700. return this;
  26701. }
  26702. }
  26703. // Multi
  26704. var multiMaterials = this.getScene().multiMaterials;
  26705. for (index = multiMaterials.length - 1; index > -1; index--) {
  26706. if (multiMaterials[index].id === id) {
  26707. this.material = multiMaterials[index];
  26708. return this;
  26709. }
  26710. }
  26711. return this;
  26712. };
  26713. /**
  26714. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26715. */
  26716. Mesh.prototype.getAnimatables = function () {
  26717. var results = new Array();
  26718. if (this.material) {
  26719. results.push(this.material);
  26720. }
  26721. if (this.skeleton) {
  26722. results.push(this.skeleton);
  26723. }
  26724. return results;
  26725. };
  26726. /**
  26727. * Modifies the mesh geometry according to the passed transformation matrix.
  26728. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26729. * The mesh normals are modified accordingly the same transformation.
  26730. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26731. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26732. * Returns the Mesh.
  26733. */
  26734. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26735. // Position
  26736. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26737. return this;
  26738. }
  26739. var submeshes = this.subMeshes.splice(0);
  26740. this._resetPointsArrayCache();
  26741. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26742. var temp = new Array();
  26743. var index;
  26744. for (index = 0; index < data.length; index += 3) {
  26745. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26746. }
  26747. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26748. // Normals
  26749. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26750. return this;
  26751. }
  26752. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26753. temp = [];
  26754. for (index = 0; index < data.length; index += 3) {
  26755. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26756. }
  26757. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26758. // flip faces?
  26759. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26760. this.flipFaces();
  26761. }
  26762. // Restore submeshes
  26763. this.releaseSubMeshes();
  26764. this.subMeshes = submeshes;
  26765. return this;
  26766. };
  26767. /**
  26768. * Modifies the mesh geometry according to its own current World Matrix.
  26769. * The mesh World Matrix is then reset.
  26770. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26771. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26772. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26773. * Returns the Mesh.
  26774. */
  26775. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26776. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26777. this.scaling.copyFromFloats(1, 1, 1);
  26778. this.position.copyFromFloats(0, 0, 0);
  26779. this.rotation.copyFromFloats(0, 0, 0);
  26780. //only if quaternion is already set
  26781. if (this.rotationQuaternion) {
  26782. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26783. }
  26784. this._worldMatrix = BABYLON.Matrix.Identity();
  26785. return this;
  26786. };
  26787. Object.defineProperty(Mesh.prototype, "_positions", {
  26788. // Cache
  26789. get: function () {
  26790. if (this._geometry) {
  26791. return this._geometry._positions;
  26792. }
  26793. return null;
  26794. },
  26795. enumerable: true,
  26796. configurable: true
  26797. });
  26798. Mesh.prototype._resetPointsArrayCache = function () {
  26799. if (this._geometry) {
  26800. this._geometry._resetPointsArrayCache();
  26801. }
  26802. return this;
  26803. };
  26804. Mesh.prototype._generatePointsArray = function () {
  26805. if (this._geometry) {
  26806. return this._geometry._generatePointsArray();
  26807. }
  26808. return false;
  26809. };
  26810. /**
  26811. * Returns a new Mesh object generated from the current mesh properties.
  26812. * This method must not get confused with createInstance().
  26813. * The parameter `name` is a string, the name given to the new mesh.
  26814. * The optional parameter `newParent` can be any Node object (default `null`).
  26815. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26816. * 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.
  26817. */
  26818. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26819. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26820. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26821. };
  26822. /**
  26823. * Disposes the Mesh.
  26824. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26825. * Returns nothing.
  26826. */
  26827. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26828. var _this = this;
  26829. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26830. this.morphTargetManager = null;
  26831. if (this._geometry) {
  26832. this._geometry.releaseForMesh(this, true);
  26833. }
  26834. // Sources
  26835. var meshes = this.getScene().meshes;
  26836. meshes.forEach(function (abstractMesh) {
  26837. var mesh = abstractMesh;
  26838. if (mesh._source && mesh._source === _this) {
  26839. mesh._source = null;
  26840. }
  26841. });
  26842. this._source = null;
  26843. // Instances
  26844. if (this._instancesBuffer) {
  26845. this._instancesBuffer.dispose();
  26846. this._instancesBuffer = null;
  26847. }
  26848. while (this.instances.length) {
  26849. this.instances[0].dispose();
  26850. }
  26851. // Highlight layers.
  26852. var highlightLayers = this.getScene().highlightLayers;
  26853. for (var i = 0; i < highlightLayers.length; i++) {
  26854. var highlightLayer = highlightLayers[i];
  26855. if (highlightLayer) {
  26856. highlightLayer.removeMesh(this);
  26857. highlightLayer.removeExcludedMesh(this);
  26858. }
  26859. }
  26860. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26861. };
  26862. /**
  26863. * Modifies the mesh geometry according to a displacement map.
  26864. * 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.
  26865. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26866. * This method returns nothing.
  26867. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26868. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26869. * 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.
  26870. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26871. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26872. *
  26873. * Returns the Mesh.
  26874. */
  26875. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26876. var _this = this;
  26877. var scene = this.getScene();
  26878. var onload = function (img) {
  26879. // Getting height map data
  26880. var canvas = document.createElement("canvas");
  26881. var context = canvas.getContext("2d");
  26882. var heightMapWidth = img.width;
  26883. var heightMapHeight = img.height;
  26884. canvas.width = heightMapWidth;
  26885. canvas.height = heightMapHeight;
  26886. context.drawImage(img, 0, 0);
  26887. // Create VertexData from map data
  26888. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26889. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26890. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26891. //execute success callback, if set
  26892. if (onSuccess) {
  26893. onSuccess(_this);
  26894. }
  26895. };
  26896. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26897. return this;
  26898. };
  26899. /**
  26900. * Modifies the mesh geometry according to a displacementMap buffer.
  26901. * 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.
  26902. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26903. * This method returns nothing.
  26904. * 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.
  26905. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26906. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26907. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26908. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26909. *
  26910. * Returns the Mesh.
  26911. */
  26912. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26913. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26914. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26915. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26916. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26917. return this;
  26918. }
  26919. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26920. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26921. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26922. var position = BABYLON.Vector3.Zero();
  26923. var normal = BABYLON.Vector3.Zero();
  26924. var uv = BABYLON.Vector2.Zero();
  26925. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26926. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26927. for (var index = 0; index < positions.length; index += 3) {
  26928. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26929. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26930. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26931. // Compute height
  26932. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26933. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26934. var pos = (u + v * heightMapWidth) * 4;
  26935. var r = buffer[pos] / 255.0;
  26936. var g = buffer[pos + 1] / 255.0;
  26937. var b = buffer[pos + 2] / 255.0;
  26938. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26939. normal.normalize();
  26940. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26941. position = position.add(normal);
  26942. position.toArray(positions, index);
  26943. }
  26944. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26945. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26946. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26947. return this;
  26948. };
  26949. /**
  26950. * Modify the mesh to get a flat shading rendering.
  26951. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26952. * This method returns the Mesh.
  26953. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26954. */
  26955. Mesh.prototype.convertToFlatShadedMesh = function () {
  26956. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26957. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26958. var kinds = this.getVerticesDataKinds();
  26959. var vbs = {};
  26960. var data = {};
  26961. var newdata = {};
  26962. var updatableNormals = false;
  26963. var kindIndex;
  26964. var kind;
  26965. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26966. kind = kinds[kindIndex];
  26967. var vertexBuffer = this.getVertexBuffer(kind);
  26968. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26969. updatableNormals = vertexBuffer.isUpdatable();
  26970. kinds.splice(kindIndex, 1);
  26971. kindIndex--;
  26972. continue;
  26973. }
  26974. vbs[kind] = vertexBuffer;
  26975. data[kind] = vbs[kind].getData();
  26976. newdata[kind] = [];
  26977. }
  26978. // Save previous submeshes
  26979. var previousSubmeshes = this.subMeshes.slice(0);
  26980. var indices = this.getIndices();
  26981. var totalIndices = this.getTotalIndices();
  26982. // Generating unique vertices per face
  26983. var index;
  26984. for (index = 0; index < totalIndices; index++) {
  26985. var vertexIndex = indices[index];
  26986. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26987. kind = kinds[kindIndex];
  26988. var stride = vbs[kind].getStrideSize();
  26989. for (var offset = 0; offset < stride; offset++) {
  26990. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26991. }
  26992. }
  26993. }
  26994. // Updating faces & normal
  26995. var normals = [];
  26996. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26997. for (index = 0; index < totalIndices; index += 3) {
  26998. indices[index] = index;
  26999. indices[index + 1] = index + 1;
  27000. indices[index + 2] = index + 2;
  27001. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27002. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27003. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27004. var p1p2 = p1.subtract(p2);
  27005. var p3p2 = p3.subtract(p2);
  27006. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27007. // Store same normals for every vertex
  27008. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27009. normals.push(normal.x);
  27010. normals.push(normal.y);
  27011. normals.push(normal.z);
  27012. }
  27013. }
  27014. this.setIndices(indices);
  27015. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27016. // Updating vertex buffers
  27017. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27018. kind = kinds[kindIndex];
  27019. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27020. }
  27021. // Updating submeshes
  27022. this.releaseSubMeshes();
  27023. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27024. var previousOne = previousSubmeshes[submeshIndex];
  27025. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27026. }
  27027. this.synchronizeInstances();
  27028. return this;
  27029. };
  27030. /**
  27031. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27032. * In other words, more vertices, no more indices and a single bigger VBO.
  27033. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27034. * Returns the Mesh.
  27035. */
  27036. Mesh.prototype.convertToUnIndexedMesh = function () {
  27037. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27038. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27039. var kinds = this.getVerticesDataKinds();
  27040. var vbs = {};
  27041. var data = {};
  27042. var newdata = {};
  27043. var kindIndex;
  27044. var kind;
  27045. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27046. kind = kinds[kindIndex];
  27047. var vertexBuffer = this.getVertexBuffer(kind);
  27048. vbs[kind] = vertexBuffer;
  27049. data[kind] = vbs[kind].getData();
  27050. newdata[kind] = [];
  27051. }
  27052. // Save previous submeshes
  27053. var previousSubmeshes = this.subMeshes.slice(0);
  27054. var indices = this.getIndices();
  27055. var totalIndices = this.getTotalIndices();
  27056. // Generating unique vertices per face
  27057. var index;
  27058. for (index = 0; index < totalIndices; index++) {
  27059. var vertexIndex = indices[index];
  27060. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27061. kind = kinds[kindIndex];
  27062. var stride = vbs[kind].getStrideSize();
  27063. for (var offset = 0; offset < stride; offset++) {
  27064. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27065. }
  27066. }
  27067. }
  27068. // Updating indices
  27069. for (index = 0; index < totalIndices; index += 3) {
  27070. indices[index] = index;
  27071. indices[index + 1] = index + 1;
  27072. indices[index + 2] = index + 2;
  27073. }
  27074. this.setIndices(indices);
  27075. // Updating vertex buffers
  27076. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27077. kind = kinds[kindIndex];
  27078. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27079. }
  27080. // Updating submeshes
  27081. this.releaseSubMeshes();
  27082. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27083. var previousOne = previousSubmeshes[submeshIndex];
  27084. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27085. }
  27086. this._unIndexed = true;
  27087. this.synchronizeInstances();
  27088. return this;
  27089. };
  27090. /**
  27091. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27092. * This method returns the Mesh.
  27093. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27094. */
  27095. Mesh.prototype.flipFaces = function (flipNormals) {
  27096. if (flipNormals === void 0) { flipNormals = false; }
  27097. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27098. var i;
  27099. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27100. for (i = 0; i < vertex_data.normals.length; i++) {
  27101. vertex_data.normals[i] *= -1;
  27102. }
  27103. }
  27104. if (vertex_data.indices) {
  27105. var temp;
  27106. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27107. // reassign indices
  27108. temp = vertex_data.indices[i + 1];
  27109. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27110. vertex_data.indices[i + 2] = temp;
  27111. }
  27112. }
  27113. vertex_data.applyToMesh(this);
  27114. return this;
  27115. };
  27116. // Instances
  27117. /**
  27118. * Creates a new InstancedMesh object from the mesh model.
  27119. * An instance shares the same properties and the same material than its model.
  27120. * Only these properties of each instance can then be set individually :
  27121. * - position
  27122. * - rotation
  27123. * - rotationQuaternion
  27124. * - setPivotMatrix
  27125. * - scaling
  27126. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27127. * Warning : this method is not supported for Line mesh and LineSystem
  27128. */
  27129. Mesh.prototype.createInstance = function (name) {
  27130. return new BABYLON.InstancedMesh(name, this);
  27131. };
  27132. /**
  27133. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27134. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27135. * This method returns the Mesh.
  27136. */
  27137. Mesh.prototype.synchronizeInstances = function () {
  27138. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27139. var instance = this.instances[instanceIndex];
  27140. instance._syncSubMeshes();
  27141. }
  27142. return this;
  27143. };
  27144. /**
  27145. * Simplify the mesh according to the given array of settings.
  27146. * Function will return immediately and will simplify async. It returns the Mesh.
  27147. * @param settings a collection of simplification settings.
  27148. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27149. * @param type the type of simplification to run.
  27150. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27151. */
  27152. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27153. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27154. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27155. this.getScene().simplificationQueue.addTask({
  27156. settings: settings,
  27157. parallelProcessing: parallelProcessing,
  27158. mesh: this,
  27159. simplificationType: simplificationType,
  27160. successCallback: successCallback
  27161. });
  27162. return this;
  27163. };
  27164. /**
  27165. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27166. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27167. * This should be used together with the simplification to avoid disappearing triangles.
  27168. * Returns the Mesh.
  27169. * @param successCallback an optional success callback to be called after the optimization finished.
  27170. */
  27171. Mesh.prototype.optimizeIndices = function (successCallback) {
  27172. var _this = this;
  27173. var indices = this.getIndices();
  27174. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27175. if (!positions || !indices) {
  27176. return this;
  27177. }
  27178. var vectorPositions = new Array();
  27179. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27180. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27181. }
  27182. var dupes = new Array();
  27183. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27184. var realPos = vectorPositions.length - 1 - iteration;
  27185. var testedPosition = vectorPositions[realPos];
  27186. for (var j = 0; j < realPos; ++j) {
  27187. var againstPosition = vectorPositions[j];
  27188. if (testedPosition.equals(againstPosition)) {
  27189. dupes[realPos] = j;
  27190. break;
  27191. }
  27192. }
  27193. }, function () {
  27194. for (var i = 0; i < indices.length; ++i) {
  27195. indices[i] = dupes[indices[i]] || indices[i];
  27196. }
  27197. //indices are now reordered
  27198. var originalSubMeshes = _this.subMeshes.slice(0);
  27199. _this.setIndices(indices);
  27200. _this.subMeshes = originalSubMeshes;
  27201. if (successCallback) {
  27202. successCallback(_this);
  27203. }
  27204. });
  27205. return this;
  27206. };
  27207. Mesh.prototype.serialize = function (serializationObject) {
  27208. serializationObject.name = this.name;
  27209. serializationObject.id = this.id;
  27210. serializationObject.type = this.getClassName();
  27211. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27212. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27213. }
  27214. serializationObject.position = this.position.asArray();
  27215. if (this.rotationQuaternion) {
  27216. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27217. }
  27218. else if (this.rotation) {
  27219. serializationObject.rotation = this.rotation.asArray();
  27220. }
  27221. serializationObject.scaling = this.scaling.asArray();
  27222. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27223. serializationObject.isEnabled = this.isEnabled(false);
  27224. serializationObject.isVisible = this.isVisible;
  27225. serializationObject.infiniteDistance = this.infiniteDistance;
  27226. serializationObject.pickable = this.isPickable;
  27227. serializationObject.receiveShadows = this.receiveShadows;
  27228. serializationObject.billboardMode = this.billboardMode;
  27229. serializationObject.visibility = this.visibility;
  27230. serializationObject.checkCollisions = this.checkCollisions;
  27231. serializationObject.isBlocker = this.isBlocker;
  27232. // Parent
  27233. if (this.parent) {
  27234. serializationObject.parentId = this.parent.id;
  27235. }
  27236. // Geometry
  27237. serializationObject.isUnIndexed = this.isUnIndexed;
  27238. var geometry = this._geometry;
  27239. if (geometry) {
  27240. var geometryId = geometry.id;
  27241. serializationObject.geometryId = geometryId;
  27242. // SubMeshes
  27243. serializationObject.subMeshes = [];
  27244. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27245. var subMesh = this.subMeshes[subIndex];
  27246. serializationObject.subMeshes.push({
  27247. materialIndex: subMesh.materialIndex,
  27248. verticesStart: subMesh.verticesStart,
  27249. verticesCount: subMesh.verticesCount,
  27250. indexStart: subMesh.indexStart,
  27251. indexCount: subMesh.indexCount
  27252. });
  27253. }
  27254. }
  27255. // Material
  27256. if (this.material) {
  27257. serializationObject.materialId = this.material.id;
  27258. }
  27259. else {
  27260. this.material = null;
  27261. }
  27262. // Morph targets
  27263. if (this.morphTargetManager) {
  27264. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27265. }
  27266. // Skeleton
  27267. if (this.skeleton) {
  27268. serializationObject.skeletonId = this.skeleton.id;
  27269. }
  27270. // Physics
  27271. //TODO implement correct serialization for physics impostors.
  27272. var impostor = this.getPhysicsImpostor();
  27273. if (impostor) {
  27274. serializationObject.physicsMass = impostor.getParam("mass");
  27275. serializationObject.physicsFriction = impostor.getParam("friction");
  27276. serializationObject.physicsRestitution = impostor.getParam("mass");
  27277. serializationObject.physicsImpostor = impostor.type;
  27278. }
  27279. // Metadata
  27280. if (this.metadata) {
  27281. serializationObject.metadata = this.metadata;
  27282. }
  27283. // Instances
  27284. serializationObject.instances = [];
  27285. for (var index = 0; index < this.instances.length; index++) {
  27286. var instance = this.instances[index];
  27287. var serializationInstance = {
  27288. name: instance.name,
  27289. id: instance.id,
  27290. position: instance.position.asArray(),
  27291. scaling: instance.scaling.asArray()
  27292. };
  27293. if (instance.rotationQuaternion) {
  27294. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27295. }
  27296. else if (instance.rotation) {
  27297. serializationInstance.rotation = instance.rotation.asArray();
  27298. }
  27299. serializationObject.instances.push(serializationInstance);
  27300. // Animations
  27301. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27302. serializationInstance.ranges = instance.serializeAnimationRanges();
  27303. }
  27304. //
  27305. // Animations
  27306. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27307. serializationObject.ranges = this.serializeAnimationRanges();
  27308. // Layer mask
  27309. serializationObject.layerMask = this.layerMask;
  27310. // Alpha
  27311. serializationObject.alphaIndex = this.alphaIndex;
  27312. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27313. // Overlay
  27314. serializationObject.overlayAlpha = this.overlayAlpha;
  27315. serializationObject.overlayColor = this.overlayColor.asArray();
  27316. serializationObject.renderOverlay = this.renderOverlay;
  27317. // Fog
  27318. serializationObject.applyFog = this.applyFog;
  27319. // Action Manager
  27320. if (this.actionManager) {
  27321. serializationObject.actions = this.actionManager.serialize(this.name);
  27322. }
  27323. };
  27324. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27325. if (!this.geometry) {
  27326. return;
  27327. }
  27328. this._markSubMeshesAsAttributesDirty();
  27329. var morphTargetManager = this._morphTargetManager;
  27330. if (morphTargetManager && morphTargetManager.vertexCount) {
  27331. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27332. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27333. this.morphTargetManager = null;
  27334. return;
  27335. }
  27336. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27337. var morphTarget = morphTargetManager.getActiveTarget(index);
  27338. var positions = morphTarget.getPositions();
  27339. if (!positions) {
  27340. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27341. return;
  27342. }
  27343. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27344. var normals = morphTarget.getNormals();
  27345. if (normals) {
  27346. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27347. }
  27348. var tangents = morphTarget.getTangents();
  27349. if (tangents) {
  27350. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27351. }
  27352. }
  27353. }
  27354. else {
  27355. var index = 0;
  27356. // Positions
  27357. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27358. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27359. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27360. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27361. }
  27362. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27363. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27364. }
  27365. index++;
  27366. }
  27367. }
  27368. };
  27369. // Statics
  27370. /**
  27371. * Returns a new Mesh object parsed from the source provided.
  27372. * The parameter `parsedMesh` is the source.
  27373. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27374. */
  27375. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27376. var mesh;
  27377. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27378. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27379. }
  27380. else {
  27381. mesh = new Mesh(parsedMesh.name, scene);
  27382. }
  27383. mesh.id = parsedMesh.id;
  27384. if (BABYLON.Tags) {
  27385. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27386. }
  27387. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27388. if (parsedMesh.metadata !== undefined) {
  27389. mesh.metadata = parsedMesh.metadata;
  27390. }
  27391. if (parsedMesh.rotationQuaternion) {
  27392. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27393. }
  27394. else if (parsedMesh.rotation) {
  27395. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27396. }
  27397. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27398. if (parsedMesh.localMatrix) {
  27399. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27400. }
  27401. else if (parsedMesh.pivotMatrix) {
  27402. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27403. }
  27404. mesh.setEnabled(parsedMesh.isEnabled);
  27405. mesh.isVisible = parsedMesh.isVisible;
  27406. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27407. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27408. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27409. if (parsedMesh.applyFog !== undefined) {
  27410. mesh.applyFog = parsedMesh.applyFog;
  27411. }
  27412. if (parsedMesh.pickable !== undefined) {
  27413. mesh.isPickable = parsedMesh.pickable;
  27414. }
  27415. if (parsedMesh.alphaIndex !== undefined) {
  27416. mesh.alphaIndex = parsedMesh.alphaIndex;
  27417. }
  27418. mesh.receiveShadows = parsedMesh.receiveShadows;
  27419. mesh.billboardMode = parsedMesh.billboardMode;
  27420. if (parsedMesh.visibility !== undefined) {
  27421. mesh.visibility = parsedMesh.visibility;
  27422. }
  27423. mesh.checkCollisions = parsedMesh.checkCollisions;
  27424. if (parsedMesh.isBlocker !== undefined) {
  27425. mesh.isBlocker = parsedMesh.isBlocker;
  27426. }
  27427. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27428. // freezeWorldMatrix
  27429. if (parsedMesh.freezeWorldMatrix) {
  27430. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27431. }
  27432. // Parent
  27433. if (parsedMesh.parentId) {
  27434. mesh._waitingParentId = parsedMesh.parentId;
  27435. }
  27436. // Actions
  27437. if (parsedMesh.actions !== undefined) {
  27438. mesh._waitingActions = parsedMesh.actions;
  27439. }
  27440. // Overlay
  27441. if (parsedMesh.overlayAlpha !== undefined) {
  27442. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27443. }
  27444. if (parsedMesh.overlayColor !== undefined) {
  27445. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27446. }
  27447. if (parsedMesh.renderOverlay !== undefined) {
  27448. mesh.renderOverlay = parsedMesh.renderOverlay;
  27449. }
  27450. // Geometry
  27451. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27452. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27453. if (parsedMesh.delayLoadingFile) {
  27454. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27455. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27456. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27457. if (parsedMesh._binaryInfo) {
  27458. mesh._binaryInfo = parsedMesh._binaryInfo;
  27459. }
  27460. mesh._delayInfo = [];
  27461. if (parsedMesh.hasUVs) {
  27462. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27463. }
  27464. if (parsedMesh.hasUVs2) {
  27465. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27466. }
  27467. if (parsedMesh.hasUVs3) {
  27468. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27469. }
  27470. if (parsedMesh.hasUVs4) {
  27471. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27472. }
  27473. if (parsedMesh.hasUVs5) {
  27474. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27475. }
  27476. if (parsedMesh.hasUVs6) {
  27477. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27478. }
  27479. if (parsedMesh.hasColors) {
  27480. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27481. }
  27482. if (parsedMesh.hasMatricesIndices) {
  27483. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27484. }
  27485. if (parsedMesh.hasMatricesWeights) {
  27486. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27487. }
  27488. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27489. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27490. mesh._checkDelayState();
  27491. }
  27492. }
  27493. else {
  27494. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27495. }
  27496. // Material
  27497. if (parsedMesh.materialId) {
  27498. mesh.setMaterialByID(parsedMesh.materialId);
  27499. }
  27500. else {
  27501. mesh.material = null;
  27502. }
  27503. // Morph targets
  27504. if (parsedMesh.morphTargetManagerId > -1) {
  27505. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27506. }
  27507. // Skeleton
  27508. if (parsedMesh.skeletonId > -1) {
  27509. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27510. if (parsedMesh.numBoneInfluencers) {
  27511. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27512. }
  27513. }
  27514. // Animations
  27515. if (parsedMesh.animations) {
  27516. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27517. var parsedAnimation = parsedMesh.animations[animationIndex];
  27518. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27519. }
  27520. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27521. }
  27522. if (parsedMesh.autoAnimate) {
  27523. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27524. }
  27525. // Layer Mask
  27526. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27527. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27528. }
  27529. else {
  27530. mesh.layerMask = 0x0FFFFFFF;
  27531. }
  27532. // Physics
  27533. if (parsedMesh.physicsImpostor) {
  27534. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27535. mass: parsedMesh.physicsMass,
  27536. friction: parsedMesh.physicsFriction,
  27537. restitution: parsedMesh.physicsRestitution
  27538. }, scene);
  27539. }
  27540. // Instances
  27541. if (parsedMesh.instances) {
  27542. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27543. var parsedInstance = parsedMesh.instances[index];
  27544. var instance = mesh.createInstance(parsedInstance.name);
  27545. if (parsedInstance.id) {
  27546. instance.id = parsedInstance.id;
  27547. }
  27548. if (BABYLON.Tags) {
  27549. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27550. }
  27551. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27552. if (parsedInstance.parentId) {
  27553. instance._waitingParentId = parsedInstance.parentId;
  27554. }
  27555. if (parsedInstance.rotationQuaternion) {
  27556. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27557. }
  27558. else if (parsedInstance.rotation) {
  27559. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27560. }
  27561. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27562. instance.checkCollisions = mesh.checkCollisions;
  27563. if (parsedMesh.animations) {
  27564. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27565. parsedAnimation = parsedMesh.animations[animationIndex];
  27566. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27567. }
  27568. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27569. }
  27570. }
  27571. }
  27572. return mesh;
  27573. };
  27574. /**
  27575. * Creates a ribbon mesh.
  27576. * Please consider using the same method from the MeshBuilder class instead.
  27577. * 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.
  27578. *
  27579. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27580. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27581. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27582. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27583. * 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.
  27584. * 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.
  27585. * 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
  27586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27587. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27589. */
  27590. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27591. if (closeArray === void 0) { closeArray = false; }
  27592. if (updatable === void 0) { updatable = false; }
  27593. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27594. pathArray: pathArray,
  27595. closeArray: closeArray,
  27596. closePath: closePath,
  27597. offset: offset,
  27598. updatable: updatable,
  27599. sideOrientation: sideOrientation,
  27600. instance: instance
  27601. }, scene);
  27602. };
  27603. /**
  27604. * Creates a plane polygonal mesh. By default, this is a disc.
  27605. * Please consider using the same method from the MeshBuilder class instead.
  27606. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27607. * 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.
  27608. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27609. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27610. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27611. */
  27612. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27613. if (scene === void 0) { scene = null; }
  27614. var options = {
  27615. radius: radius,
  27616. tessellation: tessellation,
  27617. sideOrientation: sideOrientation,
  27618. updatable: updatable
  27619. };
  27620. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27621. };
  27622. /**
  27623. * Creates a box mesh.
  27624. * Please consider using the same method from the MeshBuilder class instead.
  27625. * The parameter `size` sets the size (float) of each box side (default 1).
  27626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27627. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27629. */
  27630. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27631. if (scene === void 0) { scene = null; }
  27632. var options = {
  27633. size: size,
  27634. sideOrientation: sideOrientation,
  27635. updatable: updatable
  27636. };
  27637. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27638. };
  27639. /**
  27640. * Creates a sphere mesh.
  27641. * Please consider using the same method from the MeshBuilder class instead.
  27642. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27643. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27644. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27645. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27646. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27647. */
  27648. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27649. var options = {
  27650. segments: segments,
  27651. diameterX: diameter,
  27652. diameterY: diameter,
  27653. diameterZ: diameter,
  27654. sideOrientation: sideOrientation,
  27655. updatable: updatable
  27656. };
  27657. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27658. };
  27659. /**
  27660. * Creates a cylinder or a cone mesh.
  27661. * Please consider using the same method from the MeshBuilder class instead.
  27662. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27663. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27664. * 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.
  27665. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27666. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27668. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27670. */
  27671. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27672. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27673. if (scene !== undefined) {
  27674. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27675. updatable = scene;
  27676. }
  27677. scene = subdivisions;
  27678. subdivisions = 1;
  27679. }
  27680. var options = {
  27681. height: height,
  27682. diameterTop: diameterTop,
  27683. diameterBottom: diameterBottom,
  27684. tessellation: tessellation,
  27685. subdivisions: subdivisions,
  27686. sideOrientation: sideOrientation,
  27687. updatable: updatable
  27688. };
  27689. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27690. };
  27691. // Torus (Code from SharpDX.org)
  27692. /**
  27693. * Creates a torus mesh.
  27694. * Please consider using the same method from the MeshBuilder class instead.
  27695. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27696. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27697. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27698. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27699. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27701. */
  27702. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27703. var options = {
  27704. diameter: diameter,
  27705. thickness: thickness,
  27706. tessellation: tessellation,
  27707. sideOrientation: sideOrientation,
  27708. updatable: updatable
  27709. };
  27710. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27711. };
  27712. /**
  27713. * Creates a torus knot mesh.
  27714. * Please consider using the same method from the MeshBuilder class instead.
  27715. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27716. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27717. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27718. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27719. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27720. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27721. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27722. */
  27723. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27724. var options = {
  27725. radius: radius,
  27726. tube: tube,
  27727. radialSegments: radialSegments,
  27728. tubularSegments: tubularSegments,
  27729. p: p,
  27730. q: q,
  27731. sideOrientation: sideOrientation,
  27732. updatable: updatable
  27733. };
  27734. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27735. };
  27736. /**
  27737. * Creates a line mesh.
  27738. * Please consider using the same method from the MeshBuilder class instead.
  27739. * 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.
  27740. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27741. * The parameter `points` is an array successive Vector3.
  27742. * 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
  27743. * When updating an instance, remember that only point positions can change, not the number of points.
  27744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27745. */
  27746. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27747. if (scene === void 0) { scene = null; }
  27748. if (updatable === void 0) { updatable = false; }
  27749. if (instance === void 0) { instance = null; }
  27750. var options = {
  27751. points: points,
  27752. updatable: updatable,
  27753. instance: instance
  27754. };
  27755. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27756. };
  27757. /**
  27758. * Creates a dashed line mesh.
  27759. * Please consider using the same method from the MeshBuilder class instead.
  27760. * 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.
  27761. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27762. * The parameter `points` is an array successive Vector3.
  27763. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27764. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27765. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27766. * 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
  27767. * When updating an instance, remember that only point positions can change, not the number of points.
  27768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27769. */
  27770. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27771. if (scene === void 0) { scene = null; }
  27772. var options = {
  27773. points: points,
  27774. dashSize: dashSize,
  27775. gapSize: gapSize,
  27776. dashNb: dashNb,
  27777. updatable: updatable,
  27778. instance: instance
  27779. };
  27780. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27781. };
  27782. /**
  27783. * Creates a polygon mesh.
  27784. * Please consider using the same method from the MeshBuilder class instead.
  27785. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27786. * 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.
  27787. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27788. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27789. * Remember you can only change the shape positions, not their number when updating a polygon.
  27790. */
  27791. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27792. var options = {
  27793. shape: shape,
  27794. holes: holes,
  27795. updatable: updatable,
  27796. sideOrientation: sideOrientation
  27797. };
  27798. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27799. };
  27800. /**
  27801. * Creates an extruded polygon mesh, with depth in the Y direction.
  27802. * Please consider using the same method from the MeshBuilder class instead.
  27803. */
  27804. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27805. var options = {
  27806. shape: shape,
  27807. holes: holes,
  27808. depth: depth,
  27809. updatable: updatable,
  27810. sideOrientation: sideOrientation
  27811. };
  27812. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27813. };
  27814. /**
  27815. * Creates an extruded shape mesh.
  27816. * 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.
  27817. * Please consider using the same method from the MeshBuilder class instead.
  27818. *
  27819. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27820. * 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
  27821. * extruded along the Z axis.
  27822. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27823. * 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.
  27824. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27825. * 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
  27826. * 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
  27827. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27828. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27831. */
  27832. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27833. if (scene === void 0) { scene = null; }
  27834. var options = {
  27835. shape: shape,
  27836. path: path,
  27837. scale: scale,
  27838. rotation: rotation,
  27839. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27840. sideOrientation: sideOrientation,
  27841. instance: instance,
  27842. updatable: updatable
  27843. };
  27844. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27845. };
  27846. /**
  27847. * Creates an custom extruded shape mesh.
  27848. * 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.
  27849. * Please consider using the same method from the MeshBuilder class instead.
  27850. *
  27851. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27852. * 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
  27853. * extruded along the Z axis.
  27854. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27855. * 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
  27856. * and the distance of this point from the begining of the path :
  27857. * ```javascript
  27858. * var rotationFunction = function(i, distance) {
  27859. * // do things
  27860. * return rotationValue; }
  27861. * ```
  27862. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27863. * 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
  27864. * and the distance of this point from the begining of the path :
  27865. * ```javascript
  27866. * var scaleFunction = function(i, distance) {
  27867. * // do things
  27868. * return scaleValue;}
  27869. * ```
  27870. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27871. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27872. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27873. * 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
  27874. * 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
  27875. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27876. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27877. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27879. */
  27880. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27881. var options = {
  27882. shape: shape,
  27883. path: path,
  27884. scaleFunction: scaleFunction,
  27885. rotationFunction: rotationFunction,
  27886. ribbonCloseArray: ribbonCloseArray,
  27887. ribbonClosePath: ribbonClosePath,
  27888. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27889. sideOrientation: sideOrientation,
  27890. instance: instance,
  27891. updatable: updatable
  27892. };
  27893. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27894. };
  27895. /**
  27896. * Creates lathe mesh.
  27897. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27898. * Please consider using the same method from the MeshBuilder class instead.
  27899. * 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
  27900. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27901. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27902. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27904. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27906. */
  27907. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27908. var options = {
  27909. shape: shape,
  27910. radius: radius,
  27911. tessellation: tessellation,
  27912. sideOrientation: sideOrientation,
  27913. updatable: updatable
  27914. };
  27915. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27916. };
  27917. /**
  27918. * Creates a plane mesh.
  27919. * Please consider using the same method from the MeshBuilder class instead.
  27920. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27922. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27924. */
  27925. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27926. var options = {
  27927. size: size,
  27928. width: size,
  27929. height: size,
  27930. sideOrientation: sideOrientation,
  27931. updatable: updatable
  27932. };
  27933. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27934. };
  27935. /**
  27936. * Creates a ground mesh.
  27937. * Please consider using the same method from the MeshBuilder class instead.
  27938. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27939. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27941. */
  27942. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27943. var options = {
  27944. width: width,
  27945. height: height,
  27946. subdivisions: subdivisions,
  27947. updatable: updatable
  27948. };
  27949. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27950. };
  27951. /**
  27952. * Creates a tiled ground mesh.
  27953. * Please consider using the same method from the MeshBuilder class instead.
  27954. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27955. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27956. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27957. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27958. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27959. * numbers of subdivisions on the ground width and height of each tile.
  27960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27961. */
  27962. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27963. var options = {
  27964. xmin: xmin,
  27965. zmin: zmin,
  27966. xmax: xmax,
  27967. zmax: zmax,
  27968. subdivisions: subdivisions,
  27969. precision: precision,
  27970. updatable: updatable
  27971. };
  27972. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27973. };
  27974. /**
  27975. * Creates a ground mesh from a height map.
  27976. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27977. * Please consider using the same method from the MeshBuilder class instead.
  27978. * The parameter `url` sets the URL of the height map image resource.
  27979. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27980. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27981. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27982. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27983. * 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).
  27984. * This function is passed the newly built mesh :
  27985. * ```javascript
  27986. * function(mesh) { // do things
  27987. * return; }
  27988. * ```
  27989. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27990. */
  27991. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27992. var options = {
  27993. width: width,
  27994. height: height,
  27995. subdivisions: subdivisions,
  27996. minHeight: minHeight,
  27997. maxHeight: maxHeight,
  27998. updatable: updatable,
  27999. onReady: onReady
  28000. };
  28001. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28002. };
  28003. /**
  28004. * Creates a tube mesh.
  28005. * 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.
  28006. * Please consider using the same method from the MeshBuilder class instead.
  28007. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28008. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28009. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28010. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28011. * 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.
  28012. * It must return a radius value (positive float) :
  28013. * ```javascript
  28014. * var radiusFunction = function(i, distance) {
  28015. * // do things
  28016. * return radius; }
  28017. * ```
  28018. * 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
  28019. * 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
  28020. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28021. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28022. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28023. */
  28024. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28025. var options = {
  28026. path: path,
  28027. radius: radius,
  28028. tessellation: tessellation,
  28029. radiusFunction: radiusFunction,
  28030. arc: 1,
  28031. cap: cap,
  28032. updatable: updatable,
  28033. sideOrientation: sideOrientation,
  28034. instance: instance
  28035. };
  28036. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28037. };
  28038. /**
  28039. * Creates a polyhedron mesh.
  28040. * Please consider using the same method from the MeshBuilder class instead.
  28041. * 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
  28042. * to choose the wanted type.
  28043. * The parameter `size` (positive float, default 1) sets the polygon size.
  28044. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28045. * 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`.
  28046. * 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
  28047. * 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)`).
  28048. * 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
  28049. * 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.
  28050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28053. */
  28054. Mesh.CreatePolyhedron = function (name, options, scene) {
  28055. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28056. };
  28057. /**
  28058. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28059. * Please consider using the same method from the MeshBuilder class instead.
  28060. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28061. * 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`).
  28062. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28063. * 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.
  28064. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28065. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28067. */
  28068. Mesh.CreateIcoSphere = function (name, options, scene) {
  28069. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28070. };
  28071. /**
  28072. * Creates a decal mesh.
  28073. * Please consider using the same method from the MeshBuilder class instead.
  28074. * 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.
  28075. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28076. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28077. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28078. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28079. */
  28080. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28081. var options = {
  28082. position: position,
  28083. normal: normal,
  28084. size: size,
  28085. angle: angle
  28086. };
  28087. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28088. };
  28089. // Skeletons
  28090. /**
  28091. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28092. */
  28093. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28094. if (!this._sourcePositions) {
  28095. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28096. if (!source) {
  28097. return this._sourcePositions;
  28098. }
  28099. this._sourcePositions = new Float32Array(source);
  28100. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28101. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28102. }
  28103. }
  28104. return this._sourcePositions;
  28105. };
  28106. /**
  28107. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28108. */
  28109. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28110. if (!this._sourceNormals) {
  28111. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28112. if (!source) {
  28113. return this._sourceNormals;
  28114. }
  28115. this._sourceNormals = new Float32Array(source);
  28116. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28117. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28118. }
  28119. }
  28120. return this._sourceNormals;
  28121. };
  28122. /**
  28123. * Updates the vertex buffer by applying transformation from the bones.
  28124. * Returns the Mesh.
  28125. *
  28126. * @param {skeleton} skeleton to apply
  28127. */
  28128. Mesh.prototype.applySkeleton = function (skeleton) {
  28129. if (!this.geometry) {
  28130. return this;
  28131. }
  28132. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28133. return this;
  28134. }
  28135. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28136. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28137. return this;
  28138. }
  28139. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28140. return this;
  28141. }
  28142. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28143. return this;
  28144. }
  28145. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28146. return this;
  28147. }
  28148. if (!this._sourcePositions) {
  28149. var submeshes = this.subMeshes.slice();
  28150. this.setPositionsForCPUSkinning();
  28151. this.subMeshes = submeshes;
  28152. }
  28153. if (!this._sourceNormals) {
  28154. this.setNormalsForCPUSkinning();
  28155. }
  28156. // positionsData checks for not being Float32Array will only pass at most once
  28157. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28158. if (!positionsData) {
  28159. return this;
  28160. }
  28161. if (!(positionsData instanceof Float32Array)) {
  28162. positionsData = new Float32Array(positionsData);
  28163. }
  28164. // normalsData checks for not being Float32Array will only pass at most once
  28165. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28166. if (!normalsData) {
  28167. return this;
  28168. }
  28169. if (!(normalsData instanceof Float32Array)) {
  28170. normalsData = new Float32Array(normalsData);
  28171. }
  28172. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28173. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28174. if (!matricesWeightsData || !matricesIndicesData) {
  28175. return this;
  28176. }
  28177. var needExtras = this.numBoneInfluencers > 4;
  28178. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28179. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28180. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28181. var tempVector3 = BABYLON.Vector3.Zero();
  28182. var finalMatrix = new BABYLON.Matrix();
  28183. var tempMatrix = new BABYLON.Matrix();
  28184. var matWeightIdx = 0;
  28185. var inf;
  28186. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28187. var weight;
  28188. for (inf = 0; inf < 4; inf++) {
  28189. weight = matricesWeightsData[matWeightIdx + inf];
  28190. if (weight > 0) {
  28191. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28192. finalMatrix.addToSelf(tempMatrix);
  28193. }
  28194. else
  28195. break;
  28196. }
  28197. if (needExtras) {
  28198. for (inf = 0; inf < 4; inf++) {
  28199. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28200. if (weight > 0) {
  28201. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28202. finalMatrix.addToSelf(tempMatrix);
  28203. }
  28204. else
  28205. break;
  28206. }
  28207. }
  28208. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28209. tempVector3.toArray(positionsData, index);
  28210. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28211. tempVector3.toArray(normalsData, index);
  28212. finalMatrix.reset();
  28213. }
  28214. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28215. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28216. return this;
  28217. };
  28218. // Tools
  28219. /**
  28220. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28221. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28222. */
  28223. Mesh.MinMax = function (meshes) {
  28224. var minVector = null;
  28225. var maxVector = null;
  28226. meshes.forEach(function (mesh, index, array) {
  28227. var boundingInfo = mesh.getBoundingInfo();
  28228. var boundingBox = boundingInfo.boundingBox;
  28229. if (!minVector || !maxVector) {
  28230. minVector = boundingBox.minimumWorld;
  28231. maxVector = boundingBox.maximumWorld;
  28232. }
  28233. else {
  28234. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28235. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28236. }
  28237. });
  28238. if (!minVector || !maxVector) {
  28239. return {
  28240. min: BABYLON.Vector3.Zero(),
  28241. max: BABYLON.Vector3.Zero()
  28242. };
  28243. }
  28244. return {
  28245. min: minVector,
  28246. max: maxVector
  28247. };
  28248. };
  28249. /**
  28250. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28251. */
  28252. Mesh.Center = function (meshesOrMinMaxVector) {
  28253. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28254. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28255. };
  28256. /**
  28257. * Merge the array of meshes into a single mesh for performance reasons.
  28258. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28259. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28260. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28261. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28262. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28263. */
  28264. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28265. if (disposeSource === void 0) { disposeSource = true; }
  28266. var index;
  28267. if (!allow32BitsIndices) {
  28268. var totalVertices = 0;
  28269. // Counting vertices
  28270. for (index = 0; index < meshes.length; index++) {
  28271. if (meshes[index]) {
  28272. totalVertices += meshes[index].getTotalVertices();
  28273. if (totalVertices > 65536) {
  28274. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28275. return null;
  28276. }
  28277. }
  28278. }
  28279. }
  28280. // Merge
  28281. var vertexData = null;
  28282. var otherVertexData;
  28283. var indiceArray = new Array();
  28284. var source = null;
  28285. for (index = 0; index < meshes.length; index++) {
  28286. if (meshes[index]) {
  28287. meshes[index].computeWorldMatrix(true);
  28288. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28289. otherVertexData.transform(meshes[index].getWorldMatrix());
  28290. if (vertexData) {
  28291. vertexData.merge(otherVertexData);
  28292. }
  28293. else {
  28294. vertexData = otherVertexData;
  28295. source = meshes[index];
  28296. }
  28297. if (subdivideWithSubMeshes) {
  28298. indiceArray.push(meshes[index].getTotalIndices());
  28299. }
  28300. }
  28301. }
  28302. source = source;
  28303. if (!meshSubclass) {
  28304. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28305. }
  28306. vertexData.applyToMesh(meshSubclass);
  28307. // Setting properties
  28308. meshSubclass.material = source.material;
  28309. meshSubclass.checkCollisions = source.checkCollisions;
  28310. // Cleaning
  28311. if (disposeSource) {
  28312. for (index = 0; index < meshes.length; index++) {
  28313. if (meshes[index]) {
  28314. meshes[index].dispose();
  28315. }
  28316. }
  28317. }
  28318. // Subdivide
  28319. if (subdivideWithSubMeshes) {
  28320. //-- Suppresions du submesh global
  28321. meshSubclass.releaseSubMeshes();
  28322. index = 0;
  28323. var offset = 0;
  28324. //-- aplique la subdivision en fonction du tableau d'indices
  28325. while (index < indiceArray.length) {
  28326. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28327. offset += indiceArray[index];
  28328. index++;
  28329. }
  28330. }
  28331. return meshSubclass;
  28332. };
  28333. // Consts
  28334. Mesh._FRONTSIDE = 0;
  28335. Mesh._BACKSIDE = 1;
  28336. Mesh._DOUBLESIDE = 2;
  28337. Mesh._DEFAULTSIDE = 0;
  28338. Mesh._NO_CAP = 0;
  28339. Mesh._CAP_START = 1;
  28340. Mesh._CAP_END = 2;
  28341. Mesh._CAP_ALL = 3;
  28342. return Mesh;
  28343. }(BABYLON.AbstractMesh));
  28344. BABYLON.Mesh = Mesh;
  28345. })(BABYLON || (BABYLON = {}));
  28346. //# sourceMappingURL=babylon.mesh.js.map
  28347. var BABYLON;
  28348. (function (BABYLON) {
  28349. var BaseSubMesh = /** @class */ (function () {
  28350. function BaseSubMesh() {
  28351. }
  28352. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28353. get: function () {
  28354. return this._materialEffect;
  28355. },
  28356. enumerable: true,
  28357. configurable: true
  28358. });
  28359. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28360. if (defines === void 0) { defines = null; }
  28361. if (this._materialEffect === effect) {
  28362. if (!effect) {
  28363. this._materialDefines = null;
  28364. }
  28365. return;
  28366. }
  28367. this._materialDefines = defines;
  28368. this._materialEffect = effect;
  28369. };
  28370. return BaseSubMesh;
  28371. }());
  28372. BABYLON.BaseSubMesh = BaseSubMesh;
  28373. var SubMesh = /** @class */ (function (_super) {
  28374. __extends(SubMesh, _super);
  28375. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28376. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28377. var _this = _super.call(this) || this;
  28378. _this.materialIndex = materialIndex;
  28379. _this.verticesStart = verticesStart;
  28380. _this.verticesCount = verticesCount;
  28381. _this.indexStart = indexStart;
  28382. _this.indexCount = indexCount;
  28383. _this._renderId = 0;
  28384. _this._mesh = mesh;
  28385. _this._renderingMesh = renderingMesh || mesh;
  28386. mesh.subMeshes.push(_this);
  28387. _this._trianglePlanes = [];
  28388. _this._id = mesh.subMeshes.length - 1;
  28389. if (createBoundingBox) {
  28390. _this.refreshBoundingInfo();
  28391. mesh.computeWorldMatrix(true);
  28392. }
  28393. return _this;
  28394. }
  28395. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28396. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28397. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28398. };
  28399. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28400. get: function () {
  28401. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28402. },
  28403. enumerable: true,
  28404. configurable: true
  28405. });
  28406. /**
  28407. * Returns the submesh BoudingInfo object.
  28408. */
  28409. SubMesh.prototype.getBoundingInfo = function () {
  28410. if (this.IsGlobal) {
  28411. return this._mesh.getBoundingInfo();
  28412. }
  28413. return this._boundingInfo;
  28414. };
  28415. /**
  28416. * Sets the submesh BoundingInfo.
  28417. * Return the SubMesh.
  28418. */
  28419. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28420. this._boundingInfo = boundingInfo;
  28421. return this;
  28422. };
  28423. /**
  28424. * Returns the mesh of the current submesh.
  28425. */
  28426. SubMesh.prototype.getMesh = function () {
  28427. return this._mesh;
  28428. };
  28429. /**
  28430. * Returns the rendering mesh of the submesh.
  28431. */
  28432. SubMesh.prototype.getRenderingMesh = function () {
  28433. return this._renderingMesh;
  28434. };
  28435. /**
  28436. * Returns the submesh material.
  28437. */
  28438. SubMesh.prototype.getMaterial = function () {
  28439. var rootMaterial = this._renderingMesh.material;
  28440. if (rootMaterial === null || rootMaterial === undefined) {
  28441. return this._mesh.getScene().defaultMaterial;
  28442. }
  28443. else if (rootMaterial.getSubMaterial) {
  28444. var multiMaterial = rootMaterial;
  28445. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28446. if (this._currentMaterial !== effectiveMaterial) {
  28447. this._currentMaterial = effectiveMaterial;
  28448. this._materialDefines = null;
  28449. }
  28450. return effectiveMaterial;
  28451. }
  28452. return rootMaterial;
  28453. };
  28454. // Methods
  28455. /**
  28456. * Sets a new updated BoundingInfo object to the submesh.
  28457. * Returns the SubMesh.
  28458. */
  28459. SubMesh.prototype.refreshBoundingInfo = function () {
  28460. this._lastColliderWorldVertices = null;
  28461. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28462. return this;
  28463. }
  28464. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28465. if (!data) {
  28466. this._boundingInfo = this._mesh.getBoundingInfo();
  28467. return this;
  28468. }
  28469. var indices = this._renderingMesh.getIndices();
  28470. var extend;
  28471. //is this the only submesh?
  28472. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28473. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28474. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28475. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28476. }
  28477. else {
  28478. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28479. }
  28480. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28481. return this;
  28482. };
  28483. SubMesh.prototype._checkCollision = function (collider) {
  28484. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28485. return boundingInfo._checkCollision(collider);
  28486. };
  28487. /**
  28488. * Updates the submesh BoundingInfo.
  28489. * Returns the Submesh.
  28490. */
  28491. SubMesh.prototype.updateBoundingInfo = function (world) {
  28492. var boundingInfo = this.getBoundingInfo();
  28493. if (!boundingInfo) {
  28494. this.refreshBoundingInfo();
  28495. boundingInfo = this.getBoundingInfo();
  28496. }
  28497. boundingInfo.update(world);
  28498. return this;
  28499. };
  28500. /**
  28501. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28502. * Boolean returned.
  28503. */
  28504. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28505. var boundingInfo = this.getBoundingInfo();
  28506. if (!boundingInfo) {
  28507. return false;
  28508. }
  28509. return boundingInfo.isInFrustum(frustumPlanes);
  28510. };
  28511. /**
  28512. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28513. * Boolean returned.
  28514. */
  28515. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28516. var boundingInfo = this.getBoundingInfo();
  28517. if (!boundingInfo) {
  28518. return false;
  28519. }
  28520. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28521. };
  28522. /**
  28523. * Renders the submesh.
  28524. * Returns it.
  28525. */
  28526. SubMesh.prototype.render = function (enableAlphaMode) {
  28527. this._renderingMesh.render(this, enableAlphaMode);
  28528. return this;
  28529. };
  28530. /**
  28531. * Returns a new Index Buffer.
  28532. * Type returned : WebGLBuffer.
  28533. */
  28534. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28535. if (!this._linesIndexBuffer) {
  28536. var linesIndices = [];
  28537. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28538. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28539. }
  28540. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28541. this.linesIndexCount = linesIndices.length;
  28542. }
  28543. return this._linesIndexBuffer;
  28544. };
  28545. /**
  28546. * True is the passed Ray intersects the submesh bounding box.
  28547. * Boolean returned.
  28548. */
  28549. SubMesh.prototype.canIntersects = function (ray) {
  28550. var boundingInfo = this.getBoundingInfo();
  28551. if (!boundingInfo) {
  28552. return false;
  28553. }
  28554. return ray.intersectsBox(boundingInfo.boundingBox);
  28555. };
  28556. /**
  28557. * Returns an object IntersectionInfo.
  28558. */
  28559. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28560. var intersectInfo = null;
  28561. // LineMesh first as it's also a Mesh...
  28562. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28563. var lineMesh = this._mesh;
  28564. // Line test
  28565. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28566. var p0 = positions[indices[index]];
  28567. var p1 = positions[indices[index + 1]];
  28568. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28569. if (length < 0) {
  28570. continue;
  28571. }
  28572. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28573. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28574. if (fastCheck) {
  28575. break;
  28576. }
  28577. }
  28578. }
  28579. }
  28580. else {
  28581. // Triangles test
  28582. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28583. var p0 = positions[indices[index]];
  28584. var p1 = positions[indices[index + 1]];
  28585. var p2 = positions[indices[index + 2]];
  28586. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28587. if (currentIntersectInfo) {
  28588. if (currentIntersectInfo.distance < 0) {
  28589. continue;
  28590. }
  28591. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28592. intersectInfo = currentIntersectInfo;
  28593. intersectInfo.faceId = index / 3;
  28594. if (fastCheck) {
  28595. break;
  28596. }
  28597. }
  28598. }
  28599. }
  28600. }
  28601. return intersectInfo;
  28602. };
  28603. SubMesh.prototype._rebuild = function () {
  28604. if (this._linesIndexBuffer) {
  28605. this._linesIndexBuffer = null;
  28606. }
  28607. };
  28608. // Clone
  28609. /**
  28610. * Creates a new Submesh from the passed Mesh.
  28611. */
  28612. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28613. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28614. if (!this.IsGlobal) {
  28615. var boundingInfo = this.getBoundingInfo();
  28616. if (!boundingInfo) {
  28617. return result;
  28618. }
  28619. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28620. }
  28621. return result;
  28622. };
  28623. // Dispose
  28624. /**
  28625. * Disposes the Submesh.
  28626. * Returns nothing.
  28627. */
  28628. SubMesh.prototype.dispose = function () {
  28629. if (this._linesIndexBuffer) {
  28630. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28631. this._linesIndexBuffer = null;
  28632. }
  28633. // Remove from mesh
  28634. var index = this._mesh.subMeshes.indexOf(this);
  28635. this._mesh.subMeshes.splice(index, 1);
  28636. };
  28637. // Statics
  28638. /**
  28639. * Creates a new Submesh from the passed parameters :
  28640. * - materialIndex (integer) : the index of the main mesh material.
  28641. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28642. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28643. * - mesh (Mesh) : the main mesh to create the submesh from.
  28644. * - renderingMesh (optional Mesh) : rendering mesh.
  28645. */
  28646. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28647. var minVertexIndex = Number.MAX_VALUE;
  28648. var maxVertexIndex = -Number.MAX_VALUE;
  28649. renderingMesh = (renderingMesh || mesh);
  28650. var indices = renderingMesh.getIndices();
  28651. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28652. var vertexIndex = indices[index];
  28653. if (vertexIndex < minVertexIndex)
  28654. minVertexIndex = vertexIndex;
  28655. if (vertexIndex > maxVertexIndex)
  28656. maxVertexIndex = vertexIndex;
  28657. }
  28658. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28659. };
  28660. return SubMesh;
  28661. }(BaseSubMesh));
  28662. BABYLON.SubMesh = SubMesh;
  28663. })(BABYLON || (BABYLON = {}));
  28664. //# sourceMappingURL=babylon.subMesh.js.map
  28665. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28666. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28667. s = arguments[i];
  28668. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28669. t[p] = s[p];
  28670. }
  28671. return t;
  28672. };
  28673. var BABYLON;
  28674. (function (BABYLON) {
  28675. var MaterialDefines = /** @class */ (function () {
  28676. function MaterialDefines() {
  28677. this._isDirty = true;
  28678. this._areLightsDirty = true;
  28679. this._areAttributesDirty = true;
  28680. this._areTexturesDirty = true;
  28681. this._areFresnelDirty = true;
  28682. this._areMiscDirty = true;
  28683. this._areImageProcessingDirty = true;
  28684. this._normals = false;
  28685. this._uvs = false;
  28686. this._needNormals = false;
  28687. this._needUVs = false;
  28688. }
  28689. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28690. get: function () {
  28691. return this._isDirty;
  28692. },
  28693. enumerable: true,
  28694. configurable: true
  28695. });
  28696. MaterialDefines.prototype.markAsProcessed = function () {
  28697. this._isDirty = false;
  28698. this._areAttributesDirty = false;
  28699. this._areTexturesDirty = false;
  28700. this._areFresnelDirty = false;
  28701. this._areLightsDirty = false;
  28702. this._areMiscDirty = false;
  28703. this._areImageProcessingDirty = false;
  28704. };
  28705. MaterialDefines.prototype.markAsUnprocessed = function () {
  28706. this._isDirty = true;
  28707. };
  28708. MaterialDefines.prototype.markAllAsDirty = function () {
  28709. this._areTexturesDirty = true;
  28710. this._areAttributesDirty = true;
  28711. this._areLightsDirty = true;
  28712. this._areFresnelDirty = true;
  28713. this._areMiscDirty = true;
  28714. this._areImageProcessingDirty = true;
  28715. this._isDirty = true;
  28716. };
  28717. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28718. this._areImageProcessingDirty = true;
  28719. this._isDirty = true;
  28720. };
  28721. MaterialDefines.prototype.markAsLightDirty = function () {
  28722. this._areLightsDirty = true;
  28723. this._isDirty = true;
  28724. };
  28725. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28726. this._areAttributesDirty = true;
  28727. this._isDirty = true;
  28728. };
  28729. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28730. this._areTexturesDirty = true;
  28731. this._isDirty = true;
  28732. };
  28733. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28734. this._areFresnelDirty = true;
  28735. this._isDirty = true;
  28736. };
  28737. MaterialDefines.prototype.markAsMiscDirty = function () {
  28738. this._areMiscDirty = true;
  28739. this._isDirty = true;
  28740. };
  28741. MaterialDefines.prototype.rebuild = function () {
  28742. if (this._keys) {
  28743. delete this._keys;
  28744. }
  28745. this._keys = [];
  28746. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28747. var key = _a[_i];
  28748. if (key[0] === "_") {
  28749. continue;
  28750. }
  28751. this._keys.push(key);
  28752. }
  28753. };
  28754. MaterialDefines.prototype.isEqual = function (other) {
  28755. if (this._keys.length !== other._keys.length) {
  28756. return false;
  28757. }
  28758. for (var index = 0; index < this._keys.length; index++) {
  28759. var prop = this._keys[index];
  28760. if (this[prop] !== other[prop]) {
  28761. return false;
  28762. }
  28763. }
  28764. return true;
  28765. };
  28766. MaterialDefines.prototype.cloneTo = function (other) {
  28767. if (this._keys.length !== other._keys.length) {
  28768. other._keys = this._keys.slice(0);
  28769. }
  28770. for (var index = 0; index < this._keys.length; index++) {
  28771. var prop = this._keys[index];
  28772. other[prop] = this[prop];
  28773. }
  28774. };
  28775. MaterialDefines.prototype.reset = function () {
  28776. for (var index = 0; index < this._keys.length; index++) {
  28777. var prop = this._keys[index];
  28778. if (typeof (this[prop]) === "number") {
  28779. this[prop] = 0;
  28780. }
  28781. else {
  28782. this[prop] = false;
  28783. }
  28784. }
  28785. };
  28786. MaterialDefines.prototype.toString = function () {
  28787. var result = "";
  28788. for (var index = 0; index < this._keys.length; index++) {
  28789. var prop = this._keys[index];
  28790. var value = this[prop];
  28791. if (typeof (value) === "number") {
  28792. result += "#define " + prop + " " + this[prop] + "\n";
  28793. }
  28794. else if (value) {
  28795. result += "#define " + prop + "\n";
  28796. }
  28797. }
  28798. return result;
  28799. };
  28800. return MaterialDefines;
  28801. }());
  28802. BABYLON.MaterialDefines = MaterialDefines;
  28803. var Material = /** @class */ (function () {
  28804. function Material(name, scene, doNotAdd) {
  28805. this.checkReadyOnEveryCall = false;
  28806. this.checkReadyOnlyOnce = false;
  28807. this.state = "";
  28808. this.alpha = 1.0;
  28809. this._backFaceCulling = true;
  28810. this.doNotSerialize = false;
  28811. this.storeEffectOnSubMeshes = false;
  28812. /**
  28813. * An event triggered when the material is disposed.
  28814. * @type {BABYLON.Observable}
  28815. */
  28816. this.onDisposeObservable = new BABYLON.Observable();
  28817. /**
  28818. * An event triggered when the material is bound.
  28819. * @type {BABYLON.Observable}
  28820. */
  28821. this.onBindObservable = new BABYLON.Observable();
  28822. /**
  28823. * An event triggered when the material is unbound.
  28824. * @type {BABYLON.Observable}
  28825. */
  28826. this.onUnBindObservable = new BABYLON.Observable();
  28827. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28828. this._needDepthPrePass = false;
  28829. this.disableDepthWrite = false;
  28830. this.forceDepthWrite = false;
  28831. this.separateCullingPass = false;
  28832. this._fogEnabled = true;
  28833. this.pointSize = 1.0;
  28834. this.zOffset = 0;
  28835. this._wasPreviouslyReady = false;
  28836. this._fillMode = Material.TriangleFillMode;
  28837. this.name = name;
  28838. this.id = name || BABYLON.Tools.RandomId();
  28839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28840. if (this._scene.useRightHandedSystem) {
  28841. this.sideOrientation = Material.ClockWiseSideOrientation;
  28842. }
  28843. else {
  28844. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28845. }
  28846. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28847. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28848. if (!doNotAdd) {
  28849. this._scene.materials.push(this);
  28850. }
  28851. }
  28852. Object.defineProperty(Material, "TriangleFillMode", {
  28853. get: function () {
  28854. return Material._TriangleFillMode;
  28855. },
  28856. enumerable: true,
  28857. configurable: true
  28858. });
  28859. Object.defineProperty(Material, "WireFrameFillMode", {
  28860. get: function () {
  28861. return Material._WireFrameFillMode;
  28862. },
  28863. enumerable: true,
  28864. configurable: true
  28865. });
  28866. Object.defineProperty(Material, "PointFillMode", {
  28867. get: function () {
  28868. return Material._PointFillMode;
  28869. },
  28870. enumerable: true,
  28871. configurable: true
  28872. });
  28873. Object.defineProperty(Material, "PointListDrawMode", {
  28874. get: function () {
  28875. return Material._PointListDrawMode;
  28876. },
  28877. enumerable: true,
  28878. configurable: true
  28879. });
  28880. Object.defineProperty(Material, "LineListDrawMode", {
  28881. get: function () {
  28882. return Material._LineListDrawMode;
  28883. },
  28884. enumerable: true,
  28885. configurable: true
  28886. });
  28887. Object.defineProperty(Material, "LineLoopDrawMode", {
  28888. get: function () {
  28889. return Material._LineLoopDrawMode;
  28890. },
  28891. enumerable: true,
  28892. configurable: true
  28893. });
  28894. Object.defineProperty(Material, "LineStripDrawMode", {
  28895. get: function () {
  28896. return Material._LineStripDrawMode;
  28897. },
  28898. enumerable: true,
  28899. configurable: true
  28900. });
  28901. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28902. get: function () {
  28903. return Material._TriangleStripDrawMode;
  28904. },
  28905. enumerable: true,
  28906. configurable: true
  28907. });
  28908. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28909. get: function () {
  28910. return Material._TriangleFanDrawMode;
  28911. },
  28912. enumerable: true,
  28913. configurable: true
  28914. });
  28915. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28916. get: function () {
  28917. return Material._ClockWiseSideOrientation;
  28918. },
  28919. enumerable: true,
  28920. configurable: true
  28921. });
  28922. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28923. get: function () {
  28924. return Material._CounterClockWiseSideOrientation;
  28925. },
  28926. enumerable: true,
  28927. configurable: true
  28928. });
  28929. Object.defineProperty(Material, "TextureDirtyFlag", {
  28930. get: function () {
  28931. return Material._TextureDirtyFlag;
  28932. },
  28933. enumerable: true,
  28934. configurable: true
  28935. });
  28936. Object.defineProperty(Material, "LightDirtyFlag", {
  28937. get: function () {
  28938. return Material._LightDirtyFlag;
  28939. },
  28940. enumerable: true,
  28941. configurable: true
  28942. });
  28943. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28944. get: function () {
  28945. return Material._FresnelDirtyFlag;
  28946. },
  28947. enumerable: true,
  28948. configurable: true
  28949. });
  28950. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28951. get: function () {
  28952. return Material._AttributesDirtyFlag;
  28953. },
  28954. enumerable: true,
  28955. configurable: true
  28956. });
  28957. Object.defineProperty(Material, "MiscDirtyFlag", {
  28958. get: function () {
  28959. return Material._MiscDirtyFlag;
  28960. },
  28961. enumerable: true,
  28962. configurable: true
  28963. });
  28964. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28965. get: function () {
  28966. return this._backFaceCulling;
  28967. },
  28968. set: function (value) {
  28969. if (this._backFaceCulling === value) {
  28970. return;
  28971. }
  28972. this._backFaceCulling = value;
  28973. this.markAsDirty(Material.TextureDirtyFlag);
  28974. },
  28975. enumerable: true,
  28976. configurable: true
  28977. });
  28978. Object.defineProperty(Material.prototype, "onDispose", {
  28979. set: function (callback) {
  28980. if (this._onDisposeObserver) {
  28981. this.onDisposeObservable.remove(this._onDisposeObserver);
  28982. }
  28983. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28984. },
  28985. enumerable: true,
  28986. configurable: true
  28987. });
  28988. Object.defineProperty(Material.prototype, "onBind", {
  28989. set: function (callback) {
  28990. if (this._onBindObserver) {
  28991. this.onBindObservable.remove(this._onBindObserver);
  28992. }
  28993. this._onBindObserver = this.onBindObservable.add(callback);
  28994. },
  28995. enumerable: true,
  28996. configurable: true
  28997. });
  28998. Object.defineProperty(Material.prototype, "alphaMode", {
  28999. get: function () {
  29000. return this._alphaMode;
  29001. },
  29002. set: function (value) {
  29003. if (this._alphaMode === value) {
  29004. return;
  29005. }
  29006. this._alphaMode = value;
  29007. this.markAsDirty(Material.TextureDirtyFlag);
  29008. },
  29009. enumerable: true,
  29010. configurable: true
  29011. });
  29012. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29013. get: function () {
  29014. return this._needDepthPrePass;
  29015. },
  29016. set: function (value) {
  29017. if (this._needDepthPrePass === value) {
  29018. return;
  29019. }
  29020. this._needDepthPrePass = value;
  29021. if (this._needDepthPrePass) {
  29022. this.checkReadyOnEveryCall = true;
  29023. }
  29024. },
  29025. enumerable: true,
  29026. configurable: true
  29027. });
  29028. Object.defineProperty(Material.prototype, "fogEnabled", {
  29029. get: function () {
  29030. return this._fogEnabled;
  29031. },
  29032. set: function (value) {
  29033. if (this._fogEnabled === value) {
  29034. return;
  29035. }
  29036. this._fogEnabled = value;
  29037. this.markAsDirty(Material.MiscDirtyFlag);
  29038. },
  29039. enumerable: true,
  29040. configurable: true
  29041. });
  29042. Object.defineProperty(Material.prototype, "wireframe", {
  29043. get: function () {
  29044. return this._fillMode === Material.WireFrameFillMode;
  29045. },
  29046. set: function (value) {
  29047. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29048. },
  29049. enumerable: true,
  29050. configurable: true
  29051. });
  29052. Object.defineProperty(Material.prototype, "pointsCloud", {
  29053. get: function () {
  29054. return this._fillMode === Material.PointFillMode;
  29055. },
  29056. set: function (value) {
  29057. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29058. },
  29059. enumerable: true,
  29060. configurable: true
  29061. });
  29062. Object.defineProperty(Material.prototype, "fillMode", {
  29063. get: function () {
  29064. return this._fillMode;
  29065. },
  29066. set: function (value) {
  29067. if (this._fillMode === value) {
  29068. return;
  29069. }
  29070. this._fillMode = value;
  29071. this.markAsDirty(Material.MiscDirtyFlag);
  29072. },
  29073. enumerable: true,
  29074. configurable: true
  29075. });
  29076. /**
  29077. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29078. * subclasses should override adding information pertainent to themselves
  29079. */
  29080. Material.prototype.toString = function (fullDetails) {
  29081. var ret = "Name: " + this.name;
  29082. if (fullDetails) {
  29083. }
  29084. return ret;
  29085. };
  29086. /**
  29087. * Child classes can use it to update shaders
  29088. */
  29089. Material.prototype.getClassName = function () {
  29090. return "Material";
  29091. };
  29092. Object.defineProperty(Material.prototype, "isFrozen", {
  29093. get: function () {
  29094. return this.checkReadyOnlyOnce;
  29095. },
  29096. enumerable: true,
  29097. configurable: true
  29098. });
  29099. Material.prototype.freeze = function () {
  29100. this.checkReadyOnlyOnce = true;
  29101. };
  29102. Material.prototype.unfreeze = function () {
  29103. this.checkReadyOnlyOnce = false;
  29104. };
  29105. Material.prototype.isReady = function (mesh, useInstances) {
  29106. return true;
  29107. };
  29108. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29109. return false;
  29110. };
  29111. Material.prototype.getEffect = function () {
  29112. return this._effect;
  29113. };
  29114. Material.prototype.getScene = function () {
  29115. return this._scene;
  29116. };
  29117. Material.prototype.needAlphaBlending = function () {
  29118. return (this.alpha < 1.0);
  29119. };
  29120. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29121. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29122. };
  29123. Material.prototype.needAlphaTesting = function () {
  29124. return false;
  29125. };
  29126. Material.prototype.getAlphaTestTexture = function () {
  29127. return null;
  29128. };
  29129. Material.prototype.markDirty = function () {
  29130. this._wasPreviouslyReady = false;
  29131. };
  29132. Material.prototype._preBind = function (effect, overrideOrientation) {
  29133. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29134. var engine = this._scene.getEngine();
  29135. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29136. var reverse = orientation === Material.ClockWiseSideOrientation;
  29137. engine.enableEffect(effect ? effect : this._effect);
  29138. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29139. return reverse;
  29140. };
  29141. Material.prototype.bind = function (world, mesh) {
  29142. };
  29143. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29144. };
  29145. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29146. };
  29147. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29148. sceneUbo.bindToEffect(effect, "Scene");
  29149. };
  29150. Material.prototype.bindView = function (effect) {
  29151. if (!this._useUBO) {
  29152. effect.setMatrix("view", this.getScene().getViewMatrix());
  29153. }
  29154. else {
  29155. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29156. }
  29157. };
  29158. Material.prototype.bindViewProjection = function (effect) {
  29159. if (!this._useUBO) {
  29160. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29161. }
  29162. else {
  29163. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29164. }
  29165. };
  29166. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29167. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29168. };
  29169. Material.prototype._afterBind = function (mesh) {
  29170. this._scene._cachedMaterial = this;
  29171. if (mesh) {
  29172. this._scene._cachedVisibility = mesh.visibility;
  29173. }
  29174. else {
  29175. this._scene._cachedVisibility = 1;
  29176. }
  29177. if (mesh) {
  29178. this.onBindObservable.notifyObservers(mesh);
  29179. }
  29180. if (this.disableDepthWrite) {
  29181. var engine = this._scene.getEngine();
  29182. this._cachedDepthWriteState = engine.getDepthWrite();
  29183. engine.setDepthWrite(false);
  29184. }
  29185. };
  29186. Material.prototype.unbind = function () {
  29187. this.onUnBindObservable.notifyObservers(this);
  29188. if (this.disableDepthWrite) {
  29189. var engine = this._scene.getEngine();
  29190. engine.setDepthWrite(this._cachedDepthWriteState);
  29191. }
  29192. };
  29193. Material.prototype.getActiveTextures = function () {
  29194. return [];
  29195. };
  29196. Material.prototype.hasTexture = function (texture) {
  29197. return false;
  29198. };
  29199. Material.prototype.clone = function (name) {
  29200. return null;
  29201. };
  29202. Material.prototype.getBindedMeshes = function () {
  29203. var result = new Array();
  29204. for (var index = 0; index < this._scene.meshes.length; index++) {
  29205. var mesh = this._scene.meshes[index];
  29206. if (mesh.material === this) {
  29207. result.push(mesh);
  29208. }
  29209. }
  29210. return result;
  29211. };
  29212. /**
  29213. * Force shader compilation including textures ready check
  29214. */
  29215. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29216. var _this = this;
  29217. var localOptions = __assign({ clipPlane: false }, options);
  29218. var subMesh = new BABYLON.BaseSubMesh();
  29219. var scene = this.getScene();
  29220. var checkReady = function () {
  29221. if (!_this._scene || !_this._scene.getEngine()) {
  29222. return;
  29223. }
  29224. if (subMesh._materialDefines) {
  29225. subMesh._materialDefines._renderId = -1;
  29226. }
  29227. var clipPlaneState = scene.clipPlane;
  29228. if (localOptions.clipPlane) {
  29229. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29230. }
  29231. if (_this.storeEffectOnSubMeshes) {
  29232. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29233. if (onCompiled) {
  29234. onCompiled(_this);
  29235. }
  29236. }
  29237. else {
  29238. setTimeout(checkReady, 16);
  29239. }
  29240. }
  29241. else {
  29242. if (_this.isReady(mesh)) {
  29243. if (onCompiled) {
  29244. onCompiled(_this);
  29245. }
  29246. }
  29247. else {
  29248. setTimeout(checkReady, 16);
  29249. }
  29250. }
  29251. if (options && options.clipPlane) {
  29252. scene.clipPlane = clipPlaneState;
  29253. }
  29254. };
  29255. checkReady();
  29256. };
  29257. Material.prototype.markAsDirty = function (flag) {
  29258. if (flag & Material.TextureDirtyFlag) {
  29259. this._markAllSubMeshesAsTexturesDirty();
  29260. }
  29261. if (flag & Material.LightDirtyFlag) {
  29262. this._markAllSubMeshesAsLightsDirty();
  29263. }
  29264. if (flag & Material.FresnelDirtyFlag) {
  29265. this._markAllSubMeshesAsFresnelDirty();
  29266. }
  29267. if (flag & Material.AttributesDirtyFlag) {
  29268. this._markAllSubMeshesAsAttributesDirty();
  29269. }
  29270. if (flag & Material.MiscDirtyFlag) {
  29271. this._markAllSubMeshesAsMiscDirty();
  29272. }
  29273. this.getScene().resetCachedMaterial();
  29274. };
  29275. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29276. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29277. var mesh = _a[_i];
  29278. if (!mesh.subMeshes) {
  29279. continue;
  29280. }
  29281. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29282. var subMesh = _c[_b];
  29283. if (subMesh.getMaterial() !== this) {
  29284. continue;
  29285. }
  29286. if (!subMesh._materialDefines) {
  29287. continue;
  29288. }
  29289. func(subMesh._materialDefines);
  29290. }
  29291. }
  29292. };
  29293. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29294. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29295. };
  29296. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29297. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29298. };
  29299. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29300. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29301. };
  29302. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29303. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29304. };
  29305. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29306. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29307. };
  29308. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29309. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29310. };
  29311. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29312. // Animations
  29313. this.getScene().stopAnimation(this);
  29314. // Remove from scene
  29315. var index = this._scene.materials.indexOf(this);
  29316. if (index >= 0) {
  29317. this._scene.materials.splice(index, 1);
  29318. }
  29319. // Remove from meshes
  29320. for (index = 0; index < this._scene.meshes.length; index++) {
  29321. var mesh = this._scene.meshes[index];
  29322. if (mesh.material === this) {
  29323. mesh.material = null;
  29324. if (mesh.geometry) {
  29325. var geometry = (mesh.geometry);
  29326. if (this.storeEffectOnSubMeshes) {
  29327. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29328. var subMesh = _a[_i];
  29329. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29330. if (forceDisposeEffect && subMesh._materialEffect) {
  29331. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29332. }
  29333. }
  29334. }
  29335. else {
  29336. geometry._releaseVertexArrayObject(this._effect);
  29337. }
  29338. }
  29339. }
  29340. }
  29341. this._uniformBuffer.dispose();
  29342. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29343. if (forceDisposeEffect && this._effect) {
  29344. if (!this.storeEffectOnSubMeshes) {
  29345. this._scene.getEngine()._releaseEffect(this._effect);
  29346. }
  29347. this._effect = null;
  29348. }
  29349. // Callback
  29350. this.onDisposeObservable.notifyObservers(this);
  29351. this.onDisposeObservable.clear();
  29352. this.onBindObservable.clear();
  29353. this.onUnBindObservable.clear();
  29354. };
  29355. Material.prototype.serialize = function () {
  29356. return BABYLON.SerializationHelper.Serialize(this);
  29357. };
  29358. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29359. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29360. multiMaterial.id = parsedMultiMaterial.id;
  29361. if (BABYLON.Tags) {
  29362. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29363. }
  29364. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29365. var subMatId = parsedMultiMaterial.materials[matIndex];
  29366. if (subMatId) {
  29367. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29368. }
  29369. else {
  29370. multiMaterial.subMaterials.push(null);
  29371. }
  29372. }
  29373. return multiMaterial;
  29374. };
  29375. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29376. if (!parsedMaterial.customType) {
  29377. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29378. }
  29379. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29380. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29381. if (!BABYLON.LegacyPBRMaterial) {
  29382. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29383. return;
  29384. }
  29385. }
  29386. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29387. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29388. ;
  29389. };
  29390. // Triangle views
  29391. Material._TriangleFillMode = 0;
  29392. Material._WireFrameFillMode = 1;
  29393. Material._PointFillMode = 2;
  29394. // Draw modes
  29395. Material._PointListDrawMode = 3;
  29396. Material._LineListDrawMode = 4;
  29397. Material._LineLoopDrawMode = 5;
  29398. Material._LineStripDrawMode = 6;
  29399. Material._TriangleStripDrawMode = 7;
  29400. Material._TriangleFanDrawMode = 8;
  29401. Material._ClockWiseSideOrientation = 0;
  29402. Material._CounterClockWiseSideOrientation = 1;
  29403. Material._TextureDirtyFlag = 1;
  29404. Material._LightDirtyFlag = 2;
  29405. Material._FresnelDirtyFlag = 4;
  29406. Material._AttributesDirtyFlag = 8;
  29407. Material._MiscDirtyFlag = 16;
  29408. __decorate([
  29409. BABYLON.serialize()
  29410. ], Material.prototype, "id", void 0);
  29411. __decorate([
  29412. BABYLON.serialize()
  29413. ], Material.prototype, "name", void 0);
  29414. __decorate([
  29415. BABYLON.serialize()
  29416. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29417. __decorate([
  29418. BABYLON.serialize()
  29419. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29420. __decorate([
  29421. BABYLON.serialize()
  29422. ], Material.prototype, "state", void 0);
  29423. __decorate([
  29424. BABYLON.serialize()
  29425. ], Material.prototype, "alpha", void 0);
  29426. __decorate([
  29427. BABYLON.serialize("backFaceCulling")
  29428. ], Material.prototype, "_backFaceCulling", void 0);
  29429. __decorate([
  29430. BABYLON.serialize()
  29431. ], Material.prototype, "sideOrientation", void 0);
  29432. __decorate([
  29433. BABYLON.serialize("alphaMode")
  29434. ], Material.prototype, "_alphaMode", void 0);
  29435. __decorate([
  29436. BABYLON.serialize()
  29437. ], Material.prototype, "_needDepthPrePass", void 0);
  29438. __decorate([
  29439. BABYLON.serialize()
  29440. ], Material.prototype, "disableDepthWrite", void 0);
  29441. __decorate([
  29442. BABYLON.serialize()
  29443. ], Material.prototype, "forceDepthWrite", void 0);
  29444. __decorate([
  29445. BABYLON.serialize()
  29446. ], Material.prototype, "separateCullingPass", void 0);
  29447. __decorate([
  29448. BABYLON.serialize("fogEnabled")
  29449. ], Material.prototype, "_fogEnabled", void 0);
  29450. __decorate([
  29451. BABYLON.serialize()
  29452. ], Material.prototype, "pointSize", void 0);
  29453. __decorate([
  29454. BABYLON.serialize()
  29455. ], Material.prototype, "zOffset", void 0);
  29456. __decorate([
  29457. BABYLON.serialize()
  29458. ], Material.prototype, "wireframe", null);
  29459. __decorate([
  29460. BABYLON.serialize()
  29461. ], Material.prototype, "pointsCloud", null);
  29462. __decorate([
  29463. BABYLON.serialize()
  29464. ], Material.prototype, "fillMode", null);
  29465. return Material;
  29466. }());
  29467. BABYLON.Material = Material;
  29468. })(BABYLON || (BABYLON = {}));
  29469. //# sourceMappingURL=babylon.material.js.map
  29470. var BABYLON;
  29471. (function (BABYLON) {
  29472. var UniformBuffer = /** @class */ (function () {
  29473. /**
  29474. * Uniform buffer objects.
  29475. *
  29476. * Handles blocks of uniform on the GPU.
  29477. *
  29478. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29479. *
  29480. * For more information, please refer to :
  29481. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29482. */
  29483. function UniformBuffer(engine, data, dynamic) {
  29484. this._engine = engine;
  29485. this._noUBO = !engine.supportsUniformBuffers;
  29486. this._dynamic = dynamic;
  29487. this._data = data || [];
  29488. this._uniformLocations = {};
  29489. this._uniformSizes = {};
  29490. this._uniformLocationPointer = 0;
  29491. this._needSync = false;
  29492. if (this._noUBO) {
  29493. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29494. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29495. this.updateFloat = this._updateFloatForEffect;
  29496. this.updateFloat2 = this._updateFloat2ForEffect;
  29497. this.updateFloat3 = this._updateFloat3ForEffect;
  29498. this.updateFloat4 = this._updateFloat4ForEffect;
  29499. this.updateMatrix = this._updateMatrixForEffect;
  29500. this.updateVector3 = this._updateVector3ForEffect;
  29501. this.updateVector4 = this._updateVector4ForEffect;
  29502. this.updateColor3 = this._updateColor3ForEffect;
  29503. this.updateColor4 = this._updateColor4ForEffect;
  29504. }
  29505. else {
  29506. this._engine._uniformBuffers.push(this);
  29507. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29508. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29509. this.updateFloat = this._updateFloatForUniform;
  29510. this.updateFloat2 = this._updateFloat2ForUniform;
  29511. this.updateFloat3 = this._updateFloat3ForUniform;
  29512. this.updateFloat4 = this._updateFloat4ForUniform;
  29513. this.updateMatrix = this._updateMatrixForUniform;
  29514. this.updateVector3 = this._updateVector3ForUniform;
  29515. this.updateVector4 = this._updateVector4ForUniform;
  29516. this.updateColor3 = this._updateColor3ForUniform;
  29517. this.updateColor4 = this._updateColor4ForUniform;
  29518. }
  29519. }
  29520. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29521. // Properties
  29522. /**
  29523. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29524. * or just falling back on setUniformXXX calls.
  29525. */
  29526. get: function () {
  29527. return !this._noUBO;
  29528. },
  29529. enumerable: true,
  29530. configurable: true
  29531. });
  29532. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29533. /**
  29534. * Indicates if the WebGL underlying uniform buffer is in sync
  29535. * with the javascript cache data.
  29536. */
  29537. get: function () {
  29538. return !this._needSync;
  29539. },
  29540. enumerable: true,
  29541. configurable: true
  29542. });
  29543. /**
  29544. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29545. * Also, a dynamic UniformBuffer will disable cache verification and always
  29546. * update the underlying WebGL uniform buffer to the GPU.
  29547. */
  29548. UniformBuffer.prototype.isDynamic = function () {
  29549. return this._dynamic !== undefined;
  29550. };
  29551. /**
  29552. * The data cache on JS side.
  29553. */
  29554. UniformBuffer.prototype.getData = function () {
  29555. return this._bufferData;
  29556. };
  29557. /**
  29558. * The underlying WebGL Uniform buffer.
  29559. */
  29560. UniformBuffer.prototype.getBuffer = function () {
  29561. return this._buffer;
  29562. };
  29563. /**
  29564. * std140 layout specifies how to align data within an UBO structure.
  29565. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29566. * for specs.
  29567. */
  29568. UniformBuffer.prototype._fillAlignment = function (size) {
  29569. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29570. // and 4x4 matrices
  29571. // TODO : change if other types are used
  29572. var alignment;
  29573. if (size <= 2) {
  29574. alignment = size;
  29575. }
  29576. else {
  29577. alignment = 4;
  29578. }
  29579. if ((this._uniformLocationPointer % alignment) !== 0) {
  29580. var oldPointer = this._uniformLocationPointer;
  29581. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29582. var diff = this._uniformLocationPointer - oldPointer;
  29583. for (var i = 0; i < diff; i++) {
  29584. this._data.push(0);
  29585. }
  29586. }
  29587. };
  29588. /**
  29589. * Adds an uniform in the buffer.
  29590. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29591. * for the layout to be correct !
  29592. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29593. * @param {number|number[]} size Data size, or data directly.
  29594. */
  29595. UniformBuffer.prototype.addUniform = function (name, size) {
  29596. if (this._noUBO) {
  29597. return;
  29598. }
  29599. if (this._uniformLocations[name] !== undefined) {
  29600. // Already existing uniform
  29601. return;
  29602. }
  29603. // This function must be called in the order of the shader layout !
  29604. // size can be the size of the uniform, or data directly
  29605. var data;
  29606. if (size instanceof Array) {
  29607. data = size;
  29608. size = data.length;
  29609. }
  29610. else {
  29611. size = size;
  29612. data = [];
  29613. // Fill with zeros
  29614. for (var i = 0; i < size; i++) {
  29615. data.push(0);
  29616. }
  29617. }
  29618. this._fillAlignment(size);
  29619. this._uniformSizes[name] = size;
  29620. this._uniformLocations[name] = this._uniformLocationPointer;
  29621. this._uniformLocationPointer += size;
  29622. for (var i = 0; i < size; i++) {
  29623. this._data.push(data[i]);
  29624. }
  29625. this._needSync = true;
  29626. };
  29627. /**
  29628. * Wrapper for addUniform.
  29629. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29630. * @param {Matrix} mat A 4x4 matrix.
  29631. */
  29632. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29633. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29634. };
  29635. /**
  29636. * Wrapper for addUniform.
  29637. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29638. * @param {number} x
  29639. * @param {number} y
  29640. */
  29641. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29642. var temp = [x, y];
  29643. this.addUniform(name, temp);
  29644. };
  29645. /**
  29646. * Wrapper for addUniform.
  29647. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29648. * @param {number} x
  29649. * @param {number} y
  29650. * @param {number} z
  29651. */
  29652. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29653. var temp = [x, y, z];
  29654. this.addUniform(name, temp);
  29655. };
  29656. /**
  29657. * Wrapper for addUniform.
  29658. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29659. * @param {Color3} color
  29660. */
  29661. UniformBuffer.prototype.addColor3 = function (name, color) {
  29662. var temp = new Array();
  29663. color.toArray(temp);
  29664. this.addUniform(name, temp);
  29665. };
  29666. /**
  29667. * Wrapper for addUniform.
  29668. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29669. * @param {Color3} color
  29670. * @param {number} alpha
  29671. */
  29672. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29673. var temp = new Array();
  29674. color.toArray(temp);
  29675. temp.push(alpha);
  29676. this.addUniform(name, temp);
  29677. };
  29678. /**
  29679. * Wrapper for addUniform.
  29680. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29681. * @param {Vector3} vector
  29682. */
  29683. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29684. var temp = new Array();
  29685. vector.toArray(temp);
  29686. this.addUniform(name, temp);
  29687. };
  29688. /**
  29689. * Wrapper for addUniform.
  29690. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29691. */
  29692. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29693. this.addUniform(name, 12);
  29694. };
  29695. /**
  29696. * Wrapper for addUniform.
  29697. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29698. */
  29699. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29700. this.addUniform(name, 8);
  29701. };
  29702. /**
  29703. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29704. */
  29705. UniformBuffer.prototype.create = function () {
  29706. if (this._noUBO) {
  29707. return;
  29708. }
  29709. if (this._buffer) {
  29710. return; // nothing to do
  29711. }
  29712. // See spec, alignment must be filled as a vec4
  29713. this._fillAlignment(4);
  29714. this._bufferData = new Float32Array(this._data);
  29715. this._rebuild();
  29716. this._needSync = true;
  29717. };
  29718. UniformBuffer.prototype._rebuild = function () {
  29719. if (this._noUBO) {
  29720. return;
  29721. }
  29722. if (this._dynamic) {
  29723. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29724. }
  29725. else {
  29726. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29727. }
  29728. };
  29729. /**
  29730. * Updates the WebGL Uniform Buffer on the GPU.
  29731. * If the `dynamic` flag is set to true, no cache comparison is done.
  29732. * Otherwise, the buffer will be updated only if the cache differs.
  29733. */
  29734. UniformBuffer.prototype.update = function () {
  29735. if (!this._buffer) {
  29736. this.create();
  29737. return;
  29738. }
  29739. if (!this._dynamic && !this._needSync) {
  29740. return;
  29741. }
  29742. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29743. this._needSync = false;
  29744. };
  29745. /**
  29746. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29747. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29748. * @param {number[]|Float32Array} data Flattened data
  29749. * @param {number} size Size of the data.
  29750. */
  29751. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29752. var location = this._uniformLocations[uniformName];
  29753. if (location === undefined) {
  29754. if (this._buffer) {
  29755. // Cannot add an uniform if the buffer is already created
  29756. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29757. return;
  29758. }
  29759. this.addUniform(uniformName, size);
  29760. location = this._uniformLocations[uniformName];
  29761. }
  29762. if (!this._buffer) {
  29763. this.create();
  29764. }
  29765. if (!this._dynamic) {
  29766. // Cache for static uniform buffers
  29767. var changed = false;
  29768. for (var i = 0; i < size; i++) {
  29769. if (this._bufferData[location + i] !== data[i]) {
  29770. changed = true;
  29771. this._bufferData[location + i] = data[i];
  29772. }
  29773. }
  29774. this._needSync = this._needSync || changed;
  29775. }
  29776. else {
  29777. // No cache for dynamic
  29778. for (var i = 0; i < size; i++) {
  29779. this._bufferData[location + i] = data[i];
  29780. }
  29781. }
  29782. };
  29783. // Update methods
  29784. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29785. // To match std140, matrix must be realigned
  29786. for (var i = 0; i < 3; i++) {
  29787. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29788. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29789. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29790. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29791. }
  29792. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29793. };
  29794. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29795. this._currentEffect.setMatrix3x3(name, matrix);
  29796. };
  29797. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29798. this._currentEffect.setMatrix2x2(name, matrix);
  29799. };
  29800. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29801. // To match std140, matrix must be realigned
  29802. for (var i = 0; i < 2; i++) {
  29803. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29804. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29805. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29806. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29807. }
  29808. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29809. };
  29810. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29811. this._currentEffect.setFloat(name, x);
  29812. };
  29813. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29814. UniformBuffer._tempBuffer[0] = x;
  29815. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29816. };
  29817. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29818. if (suffix === void 0) { suffix = ""; }
  29819. this._currentEffect.setFloat2(name + suffix, x, y);
  29820. };
  29821. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29822. if (suffix === void 0) { suffix = ""; }
  29823. UniformBuffer._tempBuffer[0] = x;
  29824. UniformBuffer._tempBuffer[1] = y;
  29825. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29826. };
  29827. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29828. if (suffix === void 0) { suffix = ""; }
  29829. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29830. };
  29831. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29832. if (suffix === void 0) { suffix = ""; }
  29833. UniformBuffer._tempBuffer[0] = x;
  29834. UniformBuffer._tempBuffer[1] = y;
  29835. UniformBuffer._tempBuffer[2] = z;
  29836. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29837. };
  29838. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29839. if (suffix === void 0) { suffix = ""; }
  29840. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29841. };
  29842. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29843. if (suffix === void 0) { suffix = ""; }
  29844. UniformBuffer._tempBuffer[0] = x;
  29845. UniformBuffer._tempBuffer[1] = y;
  29846. UniformBuffer._tempBuffer[2] = z;
  29847. UniformBuffer._tempBuffer[3] = w;
  29848. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29849. };
  29850. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29851. this._currentEffect.setMatrix(name, mat);
  29852. };
  29853. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29854. this.updateUniform(name, mat.toArray(), 16);
  29855. };
  29856. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29857. this._currentEffect.setVector3(name, vector);
  29858. };
  29859. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29860. vector.toArray(UniformBuffer._tempBuffer);
  29861. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29862. };
  29863. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29864. this._currentEffect.setVector4(name, vector);
  29865. };
  29866. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29867. vector.toArray(UniformBuffer._tempBuffer);
  29868. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29869. };
  29870. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29871. if (suffix === void 0) { suffix = ""; }
  29872. this._currentEffect.setColor3(name + suffix, color);
  29873. };
  29874. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29875. if (suffix === void 0) { suffix = ""; }
  29876. color.toArray(UniformBuffer._tempBuffer);
  29877. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29878. };
  29879. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29880. if (suffix === void 0) { suffix = ""; }
  29881. this._currentEffect.setColor4(name + suffix, color, alpha);
  29882. };
  29883. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29884. if (suffix === void 0) { suffix = ""; }
  29885. color.toArray(UniformBuffer._tempBuffer);
  29886. UniformBuffer._tempBuffer[3] = alpha;
  29887. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29888. };
  29889. /**
  29890. * Sets a sampler uniform on the effect.
  29891. * @param {string} name Name of the sampler.
  29892. * @param {Texture} texture
  29893. */
  29894. UniformBuffer.prototype.setTexture = function (name, texture) {
  29895. this._currentEffect.setTexture(name, texture);
  29896. };
  29897. /**
  29898. * Directly updates the value of the uniform in the cache AND on the GPU.
  29899. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29900. * @param {number[]|Float32Array} data Flattened data
  29901. */
  29902. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29903. this.updateUniform(uniformName, data, data.length);
  29904. this.update();
  29905. };
  29906. /**
  29907. * Binds this uniform buffer to an effect.
  29908. * @param {Effect} effect
  29909. * @param {string} name Name of the uniform block in the shader.
  29910. */
  29911. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29912. this._currentEffect = effect;
  29913. if (this._noUBO || !this._buffer) {
  29914. return;
  29915. }
  29916. effect.bindUniformBuffer(this._buffer, name);
  29917. };
  29918. /**
  29919. * Disposes the uniform buffer.
  29920. */
  29921. UniformBuffer.prototype.dispose = function () {
  29922. if (this._noUBO) {
  29923. return;
  29924. }
  29925. var index = this._engine._uniformBuffers.indexOf(this);
  29926. if (index !== -1) {
  29927. this._engine._uniformBuffers.splice(index, 1);
  29928. }
  29929. if (!this._buffer) {
  29930. return;
  29931. }
  29932. if (this._engine._releaseBuffer(this._buffer)) {
  29933. this._buffer = null;
  29934. }
  29935. };
  29936. // Pool for avoiding memory leaks
  29937. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29938. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29939. return UniformBuffer;
  29940. }());
  29941. BABYLON.UniformBuffer = UniformBuffer;
  29942. })(BABYLON || (BABYLON = {}));
  29943. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29944. var BABYLON;
  29945. (function (BABYLON) {
  29946. var VertexData = /** @class */ (function () {
  29947. function VertexData() {
  29948. }
  29949. VertexData.prototype.set = function (data, kind) {
  29950. switch (kind) {
  29951. case BABYLON.VertexBuffer.PositionKind:
  29952. this.positions = data;
  29953. break;
  29954. case BABYLON.VertexBuffer.NormalKind:
  29955. this.normals = data;
  29956. break;
  29957. case BABYLON.VertexBuffer.TangentKind:
  29958. this.tangents = data;
  29959. break;
  29960. case BABYLON.VertexBuffer.UVKind:
  29961. this.uvs = data;
  29962. break;
  29963. case BABYLON.VertexBuffer.UV2Kind:
  29964. this.uvs2 = data;
  29965. break;
  29966. case BABYLON.VertexBuffer.UV3Kind:
  29967. this.uvs3 = data;
  29968. break;
  29969. case BABYLON.VertexBuffer.UV4Kind:
  29970. this.uvs4 = data;
  29971. break;
  29972. case BABYLON.VertexBuffer.UV5Kind:
  29973. this.uvs5 = data;
  29974. break;
  29975. case BABYLON.VertexBuffer.UV6Kind:
  29976. this.uvs6 = data;
  29977. break;
  29978. case BABYLON.VertexBuffer.ColorKind:
  29979. this.colors = data;
  29980. break;
  29981. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29982. this.matricesIndices = data;
  29983. break;
  29984. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29985. this.matricesWeights = data;
  29986. break;
  29987. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29988. this.matricesIndicesExtra = data;
  29989. break;
  29990. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29991. this.matricesWeightsExtra = data;
  29992. break;
  29993. }
  29994. };
  29995. /**
  29996. * Associates the vertexData to the passed Mesh.
  29997. * Sets it as updatable or not (default `false`).
  29998. * Returns the VertexData.
  29999. */
  30000. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30001. this._applyTo(mesh, updatable);
  30002. return this;
  30003. };
  30004. /**
  30005. * Associates the vertexData to the passed Geometry.
  30006. * Sets it as updatable or not (default `false`).
  30007. * Returns the VertexData.
  30008. */
  30009. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30010. this._applyTo(geometry, updatable);
  30011. return this;
  30012. };
  30013. /**
  30014. * Updates the associated mesh.
  30015. * Returns the VertexData.
  30016. */
  30017. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30018. this._update(mesh);
  30019. return this;
  30020. };
  30021. /**
  30022. * Updates the associated geometry.
  30023. * Returns the VertexData.
  30024. */
  30025. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30026. this._update(geometry);
  30027. return this;
  30028. };
  30029. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30030. if (updatable === void 0) { updatable = false; }
  30031. if (this.positions) {
  30032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30033. }
  30034. if (this.normals) {
  30035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30036. }
  30037. if (this.tangents) {
  30038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30039. }
  30040. if (this.uvs) {
  30041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30042. }
  30043. if (this.uvs2) {
  30044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30045. }
  30046. if (this.uvs3) {
  30047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30048. }
  30049. if (this.uvs4) {
  30050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30051. }
  30052. if (this.uvs5) {
  30053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30054. }
  30055. if (this.uvs6) {
  30056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30057. }
  30058. if (this.colors) {
  30059. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30060. }
  30061. if (this.matricesIndices) {
  30062. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30063. }
  30064. if (this.matricesWeights) {
  30065. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30066. }
  30067. if (this.matricesIndicesExtra) {
  30068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30069. }
  30070. if (this.matricesWeightsExtra) {
  30071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30072. }
  30073. if (this.indices) {
  30074. meshOrGeometry.setIndices(this.indices, null, updatable);
  30075. }
  30076. return this;
  30077. };
  30078. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30079. if (this.positions) {
  30080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30081. }
  30082. if (this.normals) {
  30083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30084. }
  30085. if (this.tangents) {
  30086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30087. }
  30088. if (this.uvs) {
  30089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30090. }
  30091. if (this.uvs2) {
  30092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30093. }
  30094. if (this.uvs3) {
  30095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30096. }
  30097. if (this.uvs4) {
  30098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30099. }
  30100. if (this.uvs5) {
  30101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30102. }
  30103. if (this.uvs6) {
  30104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30105. }
  30106. if (this.colors) {
  30107. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30108. }
  30109. if (this.matricesIndices) {
  30110. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30111. }
  30112. if (this.matricesWeights) {
  30113. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30114. }
  30115. if (this.matricesIndicesExtra) {
  30116. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30117. }
  30118. if (this.matricesWeightsExtra) {
  30119. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30120. }
  30121. if (this.indices) {
  30122. meshOrGeometry.setIndices(this.indices, null);
  30123. }
  30124. return this;
  30125. };
  30126. /**
  30127. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30128. * Returns the VertexData.
  30129. */
  30130. VertexData.prototype.transform = function (matrix) {
  30131. var transformed = BABYLON.Vector3.Zero();
  30132. var index;
  30133. if (this.positions) {
  30134. var position = BABYLON.Vector3.Zero();
  30135. for (index = 0; index < this.positions.length; index += 3) {
  30136. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30137. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30138. this.positions[index] = transformed.x;
  30139. this.positions[index + 1] = transformed.y;
  30140. this.positions[index + 2] = transformed.z;
  30141. }
  30142. }
  30143. if (this.normals) {
  30144. var normal = BABYLON.Vector3.Zero();
  30145. for (index = 0; index < this.normals.length; index += 3) {
  30146. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30147. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30148. this.normals[index] = transformed.x;
  30149. this.normals[index + 1] = transformed.y;
  30150. this.normals[index + 2] = transformed.z;
  30151. }
  30152. }
  30153. if (this.tangents) {
  30154. var tangent = BABYLON.Vector4.Zero();
  30155. var tangentTransformed = BABYLON.Vector4.Zero();
  30156. for (index = 0; index < this.tangents.length; index += 4) {
  30157. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30158. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30159. this.tangents[index] = tangentTransformed.x;
  30160. this.tangents[index + 1] = tangentTransformed.y;
  30161. this.tangents[index + 2] = tangentTransformed.z;
  30162. this.tangents[index + 3] = tangentTransformed.w;
  30163. }
  30164. }
  30165. return this;
  30166. };
  30167. /**
  30168. * Merges the passed VertexData into the current one.
  30169. * Returns the modified VertexData.
  30170. */
  30171. VertexData.prototype.merge = function (other, options) {
  30172. options = options || {};
  30173. if (other.indices) {
  30174. if (!this.indices) {
  30175. this.indices = [];
  30176. }
  30177. var offset = this.positions ? this.positions.length / 3 : 0;
  30178. for (var index = 0; index < other.indices.length; index++) {
  30179. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30180. this.indices.push(other.indices[index] + offset);
  30181. }
  30182. }
  30183. this.positions = this._mergeElement(this.positions, other.positions);
  30184. if (!this.positions) {
  30185. return this;
  30186. }
  30187. var count = this.positions.length / 3;
  30188. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30189. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30190. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30191. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30192. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30193. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30194. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30195. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30196. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30197. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30198. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30199. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30200. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30201. return this;
  30202. };
  30203. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30204. if (length === void 0) { length = 0; }
  30205. if (defaultValue === void 0) { defaultValue = 0; }
  30206. if (!other && !source) {
  30207. return null;
  30208. }
  30209. if (!other) {
  30210. var padding = new Float32Array(source.length);
  30211. padding.fill(defaultValue);
  30212. return this._mergeElement(source, padding, length);
  30213. }
  30214. if (!source) {
  30215. if (length === 0 || length === other.length) {
  30216. return other;
  30217. }
  30218. var padding = new Float32Array(length - other.length);
  30219. padding.fill(defaultValue);
  30220. return this._mergeElement(padding, other, length);
  30221. }
  30222. var len = other.length + source.length;
  30223. var isSrcTypedArray = source instanceof Float32Array;
  30224. var isOthTypedArray = other instanceof Float32Array;
  30225. // use non-loop method when the source is Float32Array
  30226. if (isSrcTypedArray) {
  30227. var ret32 = new Float32Array(len);
  30228. ret32.set(source);
  30229. ret32.set(other, source.length);
  30230. return ret32;
  30231. // source is number[], when other is also use concat
  30232. }
  30233. else if (!isOthTypedArray) {
  30234. return source.concat(other);
  30235. // source is a number[], but other is a Float32Array, loop required
  30236. }
  30237. else {
  30238. var ret = source.slice(0); // copy source to a separate array
  30239. for (var i = 0, len = other.length; i < len; i++) {
  30240. ret.push(other[i]);
  30241. }
  30242. return ret;
  30243. }
  30244. };
  30245. /**
  30246. * Serializes the VertexData.
  30247. * Returns a serialized object.
  30248. */
  30249. VertexData.prototype.serialize = function () {
  30250. var serializationObject = this.serialize();
  30251. if (this.positions) {
  30252. serializationObject.positions = this.positions;
  30253. }
  30254. if (this.normals) {
  30255. serializationObject.normals = this.normals;
  30256. }
  30257. if (this.tangents) {
  30258. serializationObject.tangents = this.tangents;
  30259. }
  30260. if (this.uvs) {
  30261. serializationObject.uvs = this.uvs;
  30262. }
  30263. if (this.uvs2) {
  30264. serializationObject.uvs2 = this.uvs2;
  30265. }
  30266. if (this.uvs3) {
  30267. serializationObject.uvs3 = this.uvs3;
  30268. }
  30269. if (this.uvs4) {
  30270. serializationObject.uvs4 = this.uvs4;
  30271. }
  30272. if (this.uvs5) {
  30273. serializationObject.uvs5 = this.uvs5;
  30274. }
  30275. if (this.uvs6) {
  30276. serializationObject.uvs6 = this.uvs6;
  30277. }
  30278. if (this.colors) {
  30279. serializationObject.colors = this.colors;
  30280. }
  30281. if (this.matricesIndices) {
  30282. serializationObject.matricesIndices = this.matricesIndices;
  30283. serializationObject.matricesIndices._isExpanded = true;
  30284. }
  30285. if (this.matricesWeights) {
  30286. serializationObject.matricesWeights = this.matricesWeights;
  30287. }
  30288. if (this.matricesIndicesExtra) {
  30289. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30290. serializationObject.matricesIndicesExtra._isExpanded = true;
  30291. }
  30292. if (this.matricesWeightsExtra) {
  30293. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30294. }
  30295. serializationObject.indices = this.indices;
  30296. return serializationObject;
  30297. };
  30298. // Statics
  30299. /**
  30300. * Returns the object VertexData associated to the passed mesh.
  30301. */
  30302. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30303. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30304. };
  30305. /**
  30306. * Returns the object VertexData associated to the passed geometry.
  30307. */
  30308. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30309. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30310. };
  30311. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30312. var result = new VertexData();
  30313. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30314. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30315. }
  30316. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30317. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30318. }
  30319. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30320. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30321. }
  30322. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30323. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30324. }
  30325. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30326. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30327. }
  30328. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30329. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30330. }
  30331. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30332. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30333. }
  30334. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30335. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30336. }
  30337. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30338. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30339. }
  30340. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30341. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30342. }
  30343. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30344. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30345. }
  30346. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30347. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30348. }
  30349. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30350. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30351. }
  30352. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30353. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30354. }
  30355. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30356. return result;
  30357. };
  30358. /**
  30359. * Creates the vertexData of the Ribbon.
  30360. */
  30361. VertexData.CreateRibbon = function (options) {
  30362. var pathArray = options.pathArray;
  30363. var closeArray = options.closeArray || false;
  30364. var closePath = options.closePath || false;
  30365. var invertUV = options.invertUV || false;
  30366. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30367. var offset = options.offset || defaultOffset;
  30368. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30369. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30370. var customUV = options.uvs;
  30371. var customColors = options.colors;
  30372. var positions = [];
  30373. var indices = [];
  30374. var normals = [];
  30375. var uvs = [];
  30376. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30377. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30378. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30379. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30380. var minlg; // minimal length among all paths from pathArray
  30381. var lg = []; // array of path lengths : nb of vertex per path
  30382. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30383. var p; // path iterator
  30384. var i; // point iterator
  30385. var j; // point iterator
  30386. // if single path in pathArray
  30387. if (pathArray.length < 2) {
  30388. var ar1 = [];
  30389. var ar2 = [];
  30390. for (i = 0; i < pathArray[0].length - offset; i++) {
  30391. ar1.push(pathArray[0][i]);
  30392. ar2.push(pathArray[0][i + offset]);
  30393. }
  30394. pathArray = [ar1, ar2];
  30395. }
  30396. // positions and horizontal distances (u)
  30397. var idc = 0;
  30398. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30399. var path;
  30400. var l;
  30401. minlg = pathArray[0].length;
  30402. var vectlg;
  30403. var dist;
  30404. for (p = 0; p < pathArray.length; p++) {
  30405. uTotalDistance[p] = 0;
  30406. us[p] = [0];
  30407. path = pathArray[p];
  30408. l = path.length;
  30409. minlg = (minlg < l) ? minlg : l;
  30410. j = 0;
  30411. while (j < l) {
  30412. positions.push(path[j].x, path[j].y, path[j].z);
  30413. if (j > 0) {
  30414. vectlg = path[j].subtract(path[j - 1]).length();
  30415. dist = vectlg + uTotalDistance[p];
  30416. us[p].push(dist);
  30417. uTotalDistance[p] = dist;
  30418. }
  30419. j++;
  30420. }
  30421. if (closePath) {
  30422. j--;
  30423. positions.push(path[0].x, path[0].y, path[0].z);
  30424. vectlg = path[j].subtract(path[0]).length();
  30425. dist = vectlg + uTotalDistance[p];
  30426. us[p].push(dist);
  30427. uTotalDistance[p] = dist;
  30428. }
  30429. lg[p] = l + closePathCorr;
  30430. idx[p] = idc;
  30431. idc += (l + closePathCorr);
  30432. }
  30433. // vertical distances (v)
  30434. var path1;
  30435. var path2;
  30436. var vertex1 = null;
  30437. var vertex2 = null;
  30438. for (i = 0; i < minlg + closePathCorr; i++) {
  30439. vTotalDistance[i] = 0;
  30440. vs[i] = [0];
  30441. for (p = 0; p < pathArray.length - 1; p++) {
  30442. path1 = pathArray[p];
  30443. path2 = pathArray[p + 1];
  30444. if (i === minlg) {
  30445. vertex1 = path1[0];
  30446. vertex2 = path2[0];
  30447. }
  30448. else {
  30449. vertex1 = path1[i];
  30450. vertex2 = path2[i];
  30451. }
  30452. vectlg = vertex2.subtract(vertex1).length();
  30453. dist = vectlg + vTotalDistance[i];
  30454. vs[i].push(dist);
  30455. vTotalDistance[i] = dist;
  30456. }
  30457. if (closeArray && vertex2 && vertex1) {
  30458. path1 = pathArray[p];
  30459. path2 = pathArray[0];
  30460. if (i === minlg) {
  30461. vertex2 = path2[0];
  30462. }
  30463. vectlg = vertex2.subtract(vertex1).length();
  30464. dist = vectlg + vTotalDistance[i];
  30465. vTotalDistance[i] = dist;
  30466. }
  30467. }
  30468. // uvs
  30469. var u;
  30470. var v;
  30471. if (customUV) {
  30472. for (p = 0; p < customUV.length; p++) {
  30473. uvs.push(customUV[p].x, customUV[p].y);
  30474. }
  30475. }
  30476. else {
  30477. for (p = 0; p < pathArray.length; p++) {
  30478. for (i = 0; i < minlg + closePathCorr; i++) {
  30479. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30480. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30481. if (invertUV) {
  30482. uvs.push(v, u);
  30483. }
  30484. else {
  30485. uvs.push(u, v);
  30486. }
  30487. }
  30488. }
  30489. }
  30490. // indices
  30491. p = 0; // path index
  30492. var pi = 0; // positions array index
  30493. var l1 = lg[p] - 1; // path1 length
  30494. var l2 = lg[p + 1] - 1; // path2 length
  30495. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30496. var shft = idx[1] - idx[0]; // shift
  30497. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30498. while (pi <= min && p < path1nb) {
  30499. // 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
  30500. indices.push(pi, pi + shft, pi + 1);
  30501. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30502. pi += 1;
  30503. if (pi === min) {
  30504. p++;
  30505. if (p === lg.length - 1) {
  30506. shft = idx[0] - idx[p];
  30507. l1 = lg[p] - 1;
  30508. l2 = lg[0] - 1;
  30509. }
  30510. else {
  30511. shft = idx[p + 1] - idx[p];
  30512. l1 = lg[p] - 1;
  30513. l2 = lg[p + 1] - 1;
  30514. }
  30515. pi = idx[p];
  30516. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30517. }
  30518. }
  30519. // normals
  30520. VertexData.ComputeNormals(positions, indices, normals);
  30521. if (closePath) {
  30522. var indexFirst = 0;
  30523. var indexLast = 0;
  30524. for (p = 0; p < pathArray.length; p++) {
  30525. indexFirst = idx[p] * 3;
  30526. if (p + 1 < pathArray.length) {
  30527. indexLast = (idx[p + 1] - 1) * 3;
  30528. }
  30529. else {
  30530. indexLast = normals.length - 3;
  30531. }
  30532. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30533. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30534. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30535. normals[indexLast] = normals[indexFirst];
  30536. normals[indexLast + 1] = normals[indexFirst + 1];
  30537. normals[indexLast + 2] = normals[indexFirst + 2];
  30538. }
  30539. }
  30540. // sides
  30541. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30542. // Colors
  30543. var colors = null;
  30544. if (customColors) {
  30545. colors = new Float32Array(customColors.length * 4);
  30546. for (var c = 0; c < customColors.length; c++) {
  30547. colors[c * 4] = customColors[c].r;
  30548. colors[c * 4 + 1] = customColors[c].g;
  30549. colors[c * 4 + 2] = customColors[c].b;
  30550. colors[c * 4 + 3] = customColors[c].a;
  30551. }
  30552. }
  30553. // Result
  30554. var vertexData = new VertexData();
  30555. var positions32 = new Float32Array(positions);
  30556. var normals32 = new Float32Array(normals);
  30557. var uvs32 = new Float32Array(uvs);
  30558. vertexData.indices = indices;
  30559. vertexData.positions = positions32;
  30560. vertexData.normals = normals32;
  30561. vertexData.uvs = uvs32;
  30562. if (colors) {
  30563. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30564. }
  30565. if (closePath) {
  30566. vertexData._idx = idx;
  30567. }
  30568. return vertexData;
  30569. };
  30570. /**
  30571. * Creates the VertexData of the Box.
  30572. */
  30573. VertexData.CreateBox = function (options) {
  30574. var normalsSource = [
  30575. new BABYLON.Vector3(0, 0, 1),
  30576. new BABYLON.Vector3(0, 0, -1),
  30577. new BABYLON.Vector3(1, 0, 0),
  30578. new BABYLON.Vector3(-1, 0, 0),
  30579. new BABYLON.Vector3(0, 1, 0),
  30580. new BABYLON.Vector3(0, -1, 0)
  30581. ];
  30582. var indices = [];
  30583. var positions = [];
  30584. var normals = [];
  30585. var uvs = [];
  30586. var width = options.width || options.size || 1;
  30587. var height = options.height || options.size || 1;
  30588. var depth = options.depth || options.size || 1;
  30589. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30590. var faceUV = options.faceUV || new Array(6);
  30591. var faceColors = options.faceColors;
  30592. var colors = [];
  30593. // default face colors and UV if undefined
  30594. for (var f = 0; f < 6; f++) {
  30595. if (faceUV[f] === undefined) {
  30596. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30597. }
  30598. if (faceColors && faceColors[f] === undefined) {
  30599. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30600. }
  30601. }
  30602. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30603. // Create each face in turn.
  30604. for (var index = 0; index < normalsSource.length; index++) {
  30605. var normal = normalsSource[index];
  30606. // Get two vectors perpendicular to the face normal and to each other.
  30607. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30608. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30609. // Six indices (two triangles) per face.
  30610. var verticesLength = positions.length / 3;
  30611. indices.push(verticesLength);
  30612. indices.push(verticesLength + 1);
  30613. indices.push(verticesLength + 2);
  30614. indices.push(verticesLength);
  30615. indices.push(verticesLength + 2);
  30616. indices.push(verticesLength + 3);
  30617. // Four vertices per face.
  30618. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30619. positions.push(vertex.x, vertex.y, vertex.z);
  30620. normals.push(normal.x, normal.y, normal.z);
  30621. uvs.push(faceUV[index].z, faceUV[index].w);
  30622. if (faceColors) {
  30623. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30624. }
  30625. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30626. positions.push(vertex.x, vertex.y, vertex.z);
  30627. normals.push(normal.x, normal.y, normal.z);
  30628. uvs.push(faceUV[index].x, faceUV[index].w);
  30629. if (faceColors) {
  30630. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30631. }
  30632. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30633. positions.push(vertex.x, vertex.y, vertex.z);
  30634. normals.push(normal.x, normal.y, normal.z);
  30635. uvs.push(faceUV[index].x, faceUV[index].y);
  30636. if (faceColors) {
  30637. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30638. }
  30639. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30640. positions.push(vertex.x, vertex.y, vertex.z);
  30641. normals.push(normal.x, normal.y, normal.z);
  30642. uvs.push(faceUV[index].z, faceUV[index].y);
  30643. if (faceColors) {
  30644. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30645. }
  30646. }
  30647. // sides
  30648. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30649. // Result
  30650. var vertexData = new VertexData();
  30651. vertexData.indices = indices;
  30652. vertexData.positions = positions;
  30653. vertexData.normals = normals;
  30654. vertexData.uvs = uvs;
  30655. if (faceColors) {
  30656. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30657. vertexData.colors = totalColors;
  30658. }
  30659. return vertexData;
  30660. };
  30661. /**
  30662. * Creates the VertexData of the Sphere.
  30663. */
  30664. VertexData.CreateSphere = function (options) {
  30665. var segments = options.segments || 32;
  30666. var diameterX = options.diameterX || options.diameter || 1;
  30667. var diameterY = options.diameterY || options.diameter || 1;
  30668. var diameterZ = options.diameterZ || options.diameter || 1;
  30669. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30670. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30671. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30672. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30673. var totalZRotationSteps = 2 + segments;
  30674. var totalYRotationSteps = 2 * totalZRotationSteps;
  30675. var indices = [];
  30676. var positions = [];
  30677. var normals = [];
  30678. var uvs = [];
  30679. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30680. var normalizedZ = zRotationStep / totalZRotationSteps;
  30681. var angleZ = normalizedZ * Math.PI * slice;
  30682. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30683. var normalizedY = yRotationStep / totalYRotationSteps;
  30684. var angleY = normalizedY * Math.PI * 2 * arc;
  30685. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30686. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30687. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30688. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30689. var vertex = complete.multiply(radius);
  30690. var normal = complete.divide(radius).normalize();
  30691. positions.push(vertex.x, vertex.y, vertex.z);
  30692. normals.push(normal.x, normal.y, normal.z);
  30693. uvs.push(normalizedY, normalizedZ);
  30694. }
  30695. if (zRotationStep > 0) {
  30696. var verticesCount = positions.length / 3;
  30697. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30698. indices.push((firstIndex));
  30699. indices.push((firstIndex + 1));
  30700. indices.push(firstIndex + totalYRotationSteps + 1);
  30701. indices.push((firstIndex + totalYRotationSteps + 1));
  30702. indices.push((firstIndex + 1));
  30703. indices.push((firstIndex + totalYRotationSteps + 2));
  30704. }
  30705. }
  30706. }
  30707. // Sides
  30708. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30709. // Result
  30710. var vertexData = new VertexData();
  30711. vertexData.indices = indices;
  30712. vertexData.positions = positions;
  30713. vertexData.normals = normals;
  30714. vertexData.uvs = uvs;
  30715. return vertexData;
  30716. };
  30717. /**
  30718. * Creates the VertexData of the Cylinder or Cone.
  30719. */
  30720. VertexData.CreateCylinder = function (options) {
  30721. var height = options.height || 2;
  30722. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30723. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30724. var tessellation = options.tessellation || 24;
  30725. var subdivisions = options.subdivisions || 1;
  30726. var hasRings = options.hasRings ? true : false;
  30727. var enclose = options.enclose ? true : false;
  30728. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30729. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30730. var faceUV = options.faceUV || new Array(3);
  30731. var faceColors = options.faceColors;
  30732. // default face colors and UV if undefined
  30733. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30734. var ringNb = (hasRings) ? subdivisions : 1;
  30735. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30736. var f;
  30737. for (f = 0; f < surfaceNb; f++) {
  30738. if (faceColors && faceColors[f] === undefined) {
  30739. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30740. }
  30741. }
  30742. for (f = 0; f < surfaceNb; f++) {
  30743. if (faceUV && faceUV[f] === undefined) {
  30744. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30745. }
  30746. }
  30747. var indices = new Array();
  30748. var positions = new Array();
  30749. var normals = new Array();
  30750. var uvs = new Array();
  30751. var colors = new Array();
  30752. var angle_step = Math.PI * 2 * arc / tessellation;
  30753. var angle;
  30754. var h;
  30755. var radius;
  30756. var tan = (diameterBottom - diameterTop) / 2 / height;
  30757. var ringVertex = BABYLON.Vector3.Zero();
  30758. var ringNormal = BABYLON.Vector3.Zero();
  30759. var ringFirstVertex = BABYLON.Vector3.Zero();
  30760. var ringFirstNormal = BABYLON.Vector3.Zero();
  30761. var quadNormal = BABYLON.Vector3.Zero();
  30762. var Y = BABYLON.Axis.Y;
  30763. // positions, normals, uvs
  30764. var i;
  30765. var j;
  30766. var r;
  30767. var ringIdx = 1;
  30768. var s = 1; // surface index
  30769. var cs = 0;
  30770. var v = 0;
  30771. for (i = 0; i <= subdivisions; i++) {
  30772. h = i / subdivisions;
  30773. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30774. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30775. for (r = 0; r < ringIdx; r++) {
  30776. if (hasRings) {
  30777. s += r;
  30778. }
  30779. if (enclose) {
  30780. s += 2 * r;
  30781. }
  30782. for (j = 0; j <= tessellation; j++) {
  30783. angle = j * angle_step;
  30784. // position
  30785. ringVertex.x = Math.cos(-angle) * radius;
  30786. ringVertex.y = -height / 2 + h * height;
  30787. ringVertex.z = Math.sin(-angle) * radius;
  30788. // normal
  30789. if (diameterTop === 0 && i === subdivisions) {
  30790. // if no top cap, reuse former normals
  30791. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30792. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30793. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30794. }
  30795. else {
  30796. ringNormal.x = ringVertex.x;
  30797. ringNormal.z = ringVertex.z;
  30798. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30799. ringNormal.normalize();
  30800. }
  30801. // keep first ring vertex values for enclose
  30802. if (j === 0) {
  30803. ringFirstVertex.copyFrom(ringVertex);
  30804. ringFirstNormal.copyFrom(ringNormal);
  30805. }
  30806. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30807. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30808. if (hasRings) {
  30809. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30810. }
  30811. else {
  30812. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30813. }
  30814. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30815. if (faceColors) {
  30816. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30817. }
  30818. }
  30819. // if enclose, add four vertices and their dedicated normals
  30820. if (arc !== 1 && enclose) {
  30821. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30822. positions.push(0, ringVertex.y, 0);
  30823. positions.push(0, ringVertex.y, 0);
  30824. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30825. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30826. quadNormal.normalize();
  30827. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30828. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30829. quadNormal.normalize();
  30830. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30831. if (hasRings) {
  30832. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30833. }
  30834. else {
  30835. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30836. }
  30837. uvs.push(faceUV[s + 1].x, v);
  30838. uvs.push(faceUV[s + 1].z, v);
  30839. if (hasRings) {
  30840. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30841. }
  30842. else {
  30843. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30844. }
  30845. uvs.push(faceUV[s + 2].x, v);
  30846. uvs.push(faceUV[s + 2].z, v);
  30847. if (faceColors) {
  30848. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30849. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30850. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30851. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30852. }
  30853. }
  30854. if (cs !== s) {
  30855. cs = s;
  30856. }
  30857. }
  30858. }
  30859. // indices
  30860. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30861. var s;
  30862. i = 0;
  30863. for (s = 0; s < subdivisions; s++) {
  30864. var i0 = 0;
  30865. var i1 = 0;
  30866. var i2 = 0;
  30867. var i3 = 0;
  30868. for (j = 0; j < tessellation; j++) {
  30869. i0 = i * (e + 1) + j;
  30870. i1 = (i + 1) * (e + 1) + j;
  30871. i2 = i * (e + 1) + (j + 1);
  30872. i3 = (i + 1) * (e + 1) + (j + 1);
  30873. indices.push(i0, i1, i2);
  30874. indices.push(i3, i2, i1);
  30875. }
  30876. if (arc !== 1 && enclose) {
  30877. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30878. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30879. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30880. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30881. }
  30882. i = (hasRings) ? (i + 2) : (i + 1);
  30883. }
  30884. // Caps
  30885. var createCylinderCap = function (isTop) {
  30886. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30887. if (radius === 0) {
  30888. return;
  30889. }
  30890. // Cap positions, normals & uvs
  30891. var angle;
  30892. var circleVector;
  30893. var i;
  30894. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30895. var c = null;
  30896. if (faceColors) {
  30897. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30898. }
  30899. // cap center
  30900. var vbase = positions.length / 3;
  30901. var offset = isTop ? height / 2 : -height / 2;
  30902. var center = new BABYLON.Vector3(0, offset, 0);
  30903. positions.push(center.x, center.y, center.z);
  30904. normals.push(0, isTop ? 1 : -1, 0);
  30905. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30906. if (c) {
  30907. colors.push(c.r, c.g, c.b, c.a);
  30908. }
  30909. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30910. for (i = 0; i <= tessellation; i++) {
  30911. angle = Math.PI * 2 * i * arc / tessellation;
  30912. var cos = Math.cos(-angle);
  30913. var sin = Math.sin(-angle);
  30914. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30915. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30916. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30917. normals.push(0, isTop ? 1 : -1, 0);
  30918. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30919. if (c) {
  30920. colors.push(c.r, c.g, c.b, c.a);
  30921. }
  30922. }
  30923. // Cap indices
  30924. for (i = 0; i < tessellation; i++) {
  30925. if (!isTop) {
  30926. indices.push(vbase);
  30927. indices.push(vbase + (i + 1));
  30928. indices.push(vbase + (i + 2));
  30929. }
  30930. else {
  30931. indices.push(vbase);
  30932. indices.push(vbase + (i + 2));
  30933. indices.push(vbase + (i + 1));
  30934. }
  30935. }
  30936. };
  30937. // add caps to geometry
  30938. createCylinderCap(false);
  30939. createCylinderCap(true);
  30940. // Sides
  30941. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30942. var vertexData = new VertexData();
  30943. vertexData.indices = indices;
  30944. vertexData.positions = positions;
  30945. vertexData.normals = normals;
  30946. vertexData.uvs = uvs;
  30947. if (faceColors) {
  30948. vertexData.colors = colors;
  30949. }
  30950. return vertexData;
  30951. };
  30952. /**
  30953. * Creates the VertexData of the Torus.
  30954. */
  30955. VertexData.CreateTorus = function (options) {
  30956. var indices = [];
  30957. var positions = [];
  30958. var normals = [];
  30959. var uvs = [];
  30960. var diameter = options.diameter || 1;
  30961. var thickness = options.thickness || 0.5;
  30962. var tessellation = options.tessellation || 16;
  30963. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30964. var stride = tessellation + 1;
  30965. for (var i = 0; i <= tessellation; i++) {
  30966. var u = i / tessellation;
  30967. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30968. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30969. for (var j = 0; j <= tessellation; j++) {
  30970. var v = 1 - j / tessellation;
  30971. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30972. var dx = Math.cos(innerAngle);
  30973. var dy = Math.sin(innerAngle);
  30974. // Create a vertex.
  30975. var normal = new BABYLON.Vector3(dx, dy, 0);
  30976. var position = normal.scale(thickness / 2);
  30977. var textureCoordinate = new BABYLON.Vector2(u, v);
  30978. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30979. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30980. positions.push(position.x, position.y, position.z);
  30981. normals.push(normal.x, normal.y, normal.z);
  30982. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30983. // And create indices for two triangles.
  30984. var nextI = (i + 1) % stride;
  30985. var nextJ = (j + 1) % stride;
  30986. indices.push(i * stride + j);
  30987. indices.push(i * stride + nextJ);
  30988. indices.push(nextI * stride + j);
  30989. indices.push(i * stride + nextJ);
  30990. indices.push(nextI * stride + nextJ);
  30991. indices.push(nextI * stride + j);
  30992. }
  30993. }
  30994. // Sides
  30995. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30996. // Result
  30997. var vertexData = new VertexData();
  30998. vertexData.indices = indices;
  30999. vertexData.positions = positions;
  31000. vertexData.normals = normals;
  31001. vertexData.uvs = uvs;
  31002. return vertexData;
  31003. };
  31004. /**
  31005. * Creates the VertexData of the LineSystem.
  31006. */
  31007. VertexData.CreateLineSystem = function (options) {
  31008. var indices = [];
  31009. var positions = [];
  31010. var lines = options.lines;
  31011. var colors = options.colors;
  31012. var vertexColors = [];
  31013. var idx = 0;
  31014. for (var l = 0; l < lines.length; l++) {
  31015. var points = lines[l];
  31016. for (var index = 0; index < points.length; index++) {
  31017. positions.push(points[index].x, points[index].y, points[index].z);
  31018. if (colors) {
  31019. var color = colors[l];
  31020. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31021. }
  31022. if (index > 0) {
  31023. indices.push(idx - 1);
  31024. indices.push(idx);
  31025. }
  31026. idx++;
  31027. }
  31028. }
  31029. var vertexData = new VertexData();
  31030. vertexData.indices = indices;
  31031. vertexData.positions = positions;
  31032. if (colors) {
  31033. vertexData.colors = vertexColors;
  31034. }
  31035. return vertexData;
  31036. };
  31037. /**
  31038. * Create the VertexData of the DashedLines.
  31039. */
  31040. VertexData.CreateDashedLines = function (options) {
  31041. var dashSize = options.dashSize || 3;
  31042. var gapSize = options.gapSize || 1;
  31043. var dashNb = options.dashNb || 200;
  31044. var points = options.points;
  31045. var positions = new Array();
  31046. var indices = new Array();
  31047. var curvect = BABYLON.Vector3.Zero();
  31048. var lg = 0;
  31049. var nb = 0;
  31050. var shft = 0;
  31051. var dashshft = 0;
  31052. var curshft = 0;
  31053. var idx = 0;
  31054. var i = 0;
  31055. for (i = 0; i < points.length - 1; i++) {
  31056. points[i + 1].subtractToRef(points[i], curvect);
  31057. lg += curvect.length();
  31058. }
  31059. shft = lg / dashNb;
  31060. dashshft = dashSize * shft / (dashSize + gapSize);
  31061. for (i = 0; i < points.length - 1; i++) {
  31062. points[i + 1].subtractToRef(points[i], curvect);
  31063. nb = Math.floor(curvect.length() / shft);
  31064. curvect.normalize();
  31065. for (var j = 0; j < nb; j++) {
  31066. curshft = shft * j;
  31067. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31068. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31069. indices.push(idx, idx + 1);
  31070. idx += 2;
  31071. }
  31072. }
  31073. // Result
  31074. var vertexData = new VertexData();
  31075. vertexData.positions = positions;
  31076. vertexData.indices = indices;
  31077. return vertexData;
  31078. };
  31079. /**
  31080. * Creates the VertexData of the Ground.
  31081. */
  31082. VertexData.CreateGround = function (options) {
  31083. var indices = [];
  31084. var positions = [];
  31085. var normals = [];
  31086. var uvs = [];
  31087. var row, col;
  31088. var width = options.width || 1;
  31089. var height = options.height || 1;
  31090. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31091. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31092. for (row = 0; row <= subdivisionsY; row++) {
  31093. for (col = 0; col <= subdivisionsX; col++) {
  31094. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31095. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31096. positions.push(position.x, position.y, position.z);
  31097. normals.push(normal.x, normal.y, normal.z);
  31098. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31099. }
  31100. }
  31101. for (row = 0; row < subdivisionsY; row++) {
  31102. for (col = 0; col < subdivisionsX; col++) {
  31103. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31104. indices.push(col + 1 + row * (subdivisionsX + 1));
  31105. indices.push(col + row * (subdivisionsX + 1));
  31106. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31107. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31108. indices.push(col + row * (subdivisionsX + 1));
  31109. }
  31110. }
  31111. // Result
  31112. var vertexData = new VertexData();
  31113. vertexData.indices = indices;
  31114. vertexData.positions = positions;
  31115. vertexData.normals = normals;
  31116. vertexData.uvs = uvs;
  31117. return vertexData;
  31118. };
  31119. /**
  31120. * Creates the VertexData of the TiledGround.
  31121. */
  31122. VertexData.CreateTiledGround = function (options) {
  31123. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31124. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31125. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31126. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31127. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31128. var precision = options.precision || { w: 1, h: 1 };
  31129. var indices = new Array();
  31130. var positions = new Array();
  31131. var normals = new Array();
  31132. var uvs = new Array();
  31133. var row, col, tileRow, tileCol;
  31134. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31135. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31136. precision.w = (precision.w < 1) ? 1 : precision.w;
  31137. precision.h = (precision.h < 1) ? 1 : precision.h;
  31138. var tileSize = {
  31139. 'w': (xmax - xmin) / subdivisions.w,
  31140. 'h': (zmax - zmin) / subdivisions.h
  31141. };
  31142. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31143. // Indices
  31144. var base = positions.length / 3;
  31145. var rowLength = precision.w + 1;
  31146. for (row = 0; row < precision.h; row++) {
  31147. for (col = 0; col < precision.w; col++) {
  31148. var square = [
  31149. base + col + row * rowLength,
  31150. base + (col + 1) + row * rowLength,
  31151. base + (col + 1) + (row + 1) * rowLength,
  31152. base + col + (row + 1) * rowLength
  31153. ];
  31154. indices.push(square[1]);
  31155. indices.push(square[2]);
  31156. indices.push(square[3]);
  31157. indices.push(square[0]);
  31158. indices.push(square[1]);
  31159. indices.push(square[3]);
  31160. }
  31161. }
  31162. // Position, normals and uvs
  31163. var position = BABYLON.Vector3.Zero();
  31164. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31165. for (row = 0; row <= precision.h; row++) {
  31166. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31167. for (col = 0; col <= precision.w; col++) {
  31168. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31169. position.y = 0;
  31170. positions.push(position.x, position.y, position.z);
  31171. normals.push(normal.x, normal.y, normal.z);
  31172. uvs.push(col / precision.w, row / precision.h);
  31173. }
  31174. }
  31175. }
  31176. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31177. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31178. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31179. }
  31180. }
  31181. // Result
  31182. var vertexData = new VertexData();
  31183. vertexData.indices = indices;
  31184. vertexData.positions = positions;
  31185. vertexData.normals = normals;
  31186. vertexData.uvs = uvs;
  31187. return vertexData;
  31188. };
  31189. /**
  31190. * Creates the VertexData of the Ground designed from a heightmap.
  31191. */
  31192. VertexData.CreateGroundFromHeightMap = function (options) {
  31193. var indices = [];
  31194. var positions = [];
  31195. var normals = [];
  31196. var uvs = [];
  31197. var row, col;
  31198. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31199. // Vertices
  31200. for (row = 0; row <= options.subdivisions; row++) {
  31201. for (col = 0; col <= options.subdivisions; col++) {
  31202. 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));
  31203. // Compute height
  31204. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31205. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31206. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31207. var r = options.buffer[pos] / 255.0;
  31208. var g = options.buffer[pos + 1] / 255.0;
  31209. var b = options.buffer[pos + 2] / 255.0;
  31210. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31211. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31212. // Add vertex
  31213. positions.push(position.x, position.y, position.z);
  31214. normals.push(0, 0, 0);
  31215. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31216. }
  31217. }
  31218. // Indices
  31219. for (row = 0; row < options.subdivisions; row++) {
  31220. for (col = 0; col < options.subdivisions; col++) {
  31221. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31222. indices.push(col + 1 + row * (options.subdivisions + 1));
  31223. indices.push(col + row * (options.subdivisions + 1));
  31224. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31225. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31226. indices.push(col + row * (options.subdivisions + 1));
  31227. }
  31228. }
  31229. // Normals
  31230. VertexData.ComputeNormals(positions, indices, normals);
  31231. // Result
  31232. var vertexData = new VertexData();
  31233. vertexData.indices = indices;
  31234. vertexData.positions = positions;
  31235. vertexData.normals = normals;
  31236. vertexData.uvs = uvs;
  31237. return vertexData;
  31238. };
  31239. /**
  31240. * Creates the VertexData of the Plane.
  31241. */
  31242. VertexData.CreatePlane = function (options) {
  31243. var indices = [];
  31244. var positions = [];
  31245. var normals = [];
  31246. var uvs = [];
  31247. var width = options.width || options.size || 1;
  31248. var height = options.height || options.size || 1;
  31249. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31250. // Vertices
  31251. var halfWidth = width / 2.0;
  31252. var halfHeight = height / 2.0;
  31253. positions.push(-halfWidth, -halfHeight, 0);
  31254. normals.push(0, 0, -1.0);
  31255. uvs.push(0.0, 0.0);
  31256. positions.push(halfWidth, -halfHeight, 0);
  31257. normals.push(0, 0, -1.0);
  31258. uvs.push(1.0, 0.0);
  31259. positions.push(halfWidth, halfHeight, 0);
  31260. normals.push(0, 0, -1.0);
  31261. uvs.push(1.0, 1.0);
  31262. positions.push(-halfWidth, halfHeight, 0);
  31263. normals.push(0, 0, -1.0);
  31264. uvs.push(0.0, 1.0);
  31265. // Indices
  31266. indices.push(0);
  31267. indices.push(1);
  31268. indices.push(2);
  31269. indices.push(0);
  31270. indices.push(2);
  31271. indices.push(3);
  31272. // Sides
  31273. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31274. // Result
  31275. var vertexData = new VertexData();
  31276. vertexData.indices = indices;
  31277. vertexData.positions = positions;
  31278. vertexData.normals = normals;
  31279. vertexData.uvs = uvs;
  31280. return vertexData;
  31281. };
  31282. /**
  31283. * Creates the VertexData of the Disc or regular Polygon.
  31284. */
  31285. VertexData.CreateDisc = function (options) {
  31286. var positions = new Array();
  31287. var indices = new Array();
  31288. var normals = new Array();
  31289. var uvs = new Array();
  31290. var radius = options.radius || 0.5;
  31291. var tessellation = options.tessellation || 64;
  31292. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31293. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31294. // positions and uvs
  31295. positions.push(0, 0, 0); // disc center first
  31296. uvs.push(0.5, 0.5);
  31297. var theta = Math.PI * 2 * arc;
  31298. var step = theta / tessellation;
  31299. for (var a = 0; a < theta; a += step) {
  31300. var x = Math.cos(a);
  31301. var y = Math.sin(a);
  31302. var u = (x + 1) / 2;
  31303. var v = (1 - y) / 2;
  31304. positions.push(radius * x, radius * y, 0);
  31305. uvs.push(u, v);
  31306. }
  31307. if (arc === 1) {
  31308. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31309. uvs.push(uvs[2], uvs[3]);
  31310. }
  31311. //indices
  31312. var vertexNb = positions.length / 3;
  31313. for (var i = 1; i < vertexNb - 1; i++) {
  31314. indices.push(i + 1, 0, i);
  31315. }
  31316. // result
  31317. VertexData.ComputeNormals(positions, indices, normals);
  31318. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31319. var vertexData = new VertexData();
  31320. vertexData.indices = indices;
  31321. vertexData.positions = positions;
  31322. vertexData.normals = normals;
  31323. vertexData.uvs = uvs;
  31324. return vertexData;
  31325. };
  31326. /**
  31327. * Re-creates the VertexData of the Polygon for sideOrientation.
  31328. */
  31329. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31330. var faceUV = fUV || new Array(3);
  31331. var faceColors = fColors;
  31332. var colors = [];
  31333. // default face colors and UV if undefined
  31334. for (var f = 0; f < 3; f++) {
  31335. if (faceUV[f] === undefined) {
  31336. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31337. }
  31338. if (faceColors && faceColors[f] === undefined) {
  31339. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31340. }
  31341. }
  31342. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31343. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31344. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31345. var indices = polygon.getIndices();
  31346. // set face colours and textures
  31347. var idx = 0;
  31348. var face = 0;
  31349. for (var index = 0; index < normals.length; index += 3) {
  31350. //Edge Face no. 1
  31351. if (Math.abs(normals[index + 1]) < 0.001) {
  31352. face = 1;
  31353. }
  31354. //Top Face no. 0
  31355. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31356. face = 0;
  31357. }
  31358. //Bottom Face no. 2
  31359. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31360. face = 2;
  31361. }
  31362. idx = index / 3;
  31363. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31364. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31365. if (faceColors) {
  31366. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31367. }
  31368. }
  31369. // sides
  31370. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31371. // Result
  31372. var vertexData = new VertexData();
  31373. vertexData.indices = indices;
  31374. vertexData.positions = positions;
  31375. vertexData.normals = normals;
  31376. vertexData.uvs = uvs;
  31377. if (faceColors) {
  31378. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31379. vertexData.colors = totalColors;
  31380. }
  31381. return vertexData;
  31382. };
  31383. /**
  31384. * Creates the VertexData of the IcoSphere.
  31385. */
  31386. VertexData.CreateIcoSphere = function (options) {
  31387. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31388. var radius = options.radius || 1;
  31389. var flat = (options.flat === undefined) ? true : options.flat;
  31390. var subdivisions = options.subdivisions || 4;
  31391. var radiusX = options.radiusX || radius;
  31392. var radiusY = options.radiusY || radius;
  31393. var radiusZ = options.radiusZ || radius;
  31394. var t = (1 + Math.sqrt(5)) / 2;
  31395. // 12 vertex x,y,z
  31396. var ico_vertices = [
  31397. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31398. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31399. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31400. ];
  31401. // index of 3 vertex makes a face of icopshere
  31402. var ico_indices = [
  31403. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31404. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31405. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31406. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31407. ];
  31408. // vertex for uv have aliased position, not for UV
  31409. var vertices_unalias_id = [
  31410. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31411. // vertex alias
  31412. 0,
  31413. 2,
  31414. 3,
  31415. 3,
  31416. 3,
  31417. 4,
  31418. 7,
  31419. 8,
  31420. 9,
  31421. 9,
  31422. 10,
  31423. 11 // 23: B + 12
  31424. ];
  31425. // uv as integer step (not pixels !)
  31426. var ico_vertexuv = [
  31427. 5, 1, 3, 1, 6, 4, 0, 0,
  31428. 5, 3, 4, 2, 2, 2, 4, 0,
  31429. 2, 0, 1, 1, 6, 0, 6, 2,
  31430. // vertex alias (for same vertex on different faces)
  31431. 0, 4,
  31432. 3, 3,
  31433. 4, 4,
  31434. 3, 1,
  31435. 4, 2,
  31436. 4, 4,
  31437. 0, 2,
  31438. 1, 1,
  31439. 2, 2,
  31440. 3, 3,
  31441. 1, 3,
  31442. 2, 4 // 23: B + 12
  31443. ];
  31444. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31445. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31446. // First island of uv mapping
  31447. // v = 4h 3+ 2
  31448. // v = 3h 9+ 4
  31449. // v = 2h 9+ 5 B
  31450. // v = 1h 9 1 0
  31451. // v = 0h 3 8 7 A
  31452. // u = 0 1 2 3 4 5 6 *a
  31453. // Second island of uv mapping
  31454. // v = 4h 0+ B+ 4+
  31455. // v = 3h A+ 2+
  31456. // v = 2h 7+ 6 3+
  31457. // v = 1h 8+ 3+
  31458. // v = 0h
  31459. // u = 0 1 2 3 4 5 6 *a
  31460. // Face layout on texture UV mapping
  31461. // ============
  31462. // \ 4 /\ 16 / ======
  31463. // \ / \ / /\ 11 /
  31464. // \/ 7 \/ / \ /
  31465. // ======= / 10 \/
  31466. // /\ 17 /\ =======
  31467. // / \ / \ \ 15 /\
  31468. // / 8 \/ 12 \ \ / \
  31469. // ============ \/ 6 \
  31470. // \ 18 /\ ============
  31471. // \ / \ \ 5 /\ 0 /
  31472. // \/ 13 \ \ / \ /
  31473. // ======= \/ 1 \/
  31474. // =============
  31475. // /\ 19 /\ 2 /\
  31476. // / \ / \ / \
  31477. // / 14 \/ 9 \/ 3 \
  31478. // ===================
  31479. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31480. var ustep = 138 / 1024;
  31481. var vstep = 239 / 1024;
  31482. var uoffset = 60 / 1024;
  31483. var voffset = 26 / 1024;
  31484. // Second island should have margin, not to touch the first island
  31485. // avoid any borderline artefact in pixel rounding
  31486. var island_u_offset = -40 / 1024;
  31487. var island_v_offset = +20 / 1024;
  31488. // face is either island 0 or 1 :
  31489. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31490. var island = [
  31491. 0, 0, 0, 0, 1,
  31492. 0, 0, 1, 1, 0,
  31493. 0, 0, 1, 1, 0,
  31494. 0, 1, 1, 1, 0 // 15 - 19
  31495. ];
  31496. var indices = new Array();
  31497. var positions = new Array();
  31498. var normals = new Array();
  31499. var uvs = new Array();
  31500. var current_indice = 0;
  31501. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31502. var face_vertex_pos = new Array(3);
  31503. var face_vertex_uv = new Array(3);
  31504. var v012;
  31505. for (v012 = 0; v012 < 3; v012++) {
  31506. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31507. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31508. }
  31509. // create all with normals
  31510. for (var face = 0; face < 20; face++) {
  31511. // 3 vertex per face
  31512. for (v012 = 0; v012 < 3; v012++) {
  31513. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31514. var v_id = ico_indices[3 * face + v012];
  31515. // vertex have 3D position (x,y,z)
  31516. 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]);
  31517. // Normalize to get normal, then scale to radius
  31518. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31519. // uv Coordinates from vertex ID
  31520. 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);
  31521. }
  31522. // Subdivide the face (interpolate pos, norm, uv)
  31523. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31524. // - norm is linear interpolation of vertex corner normal
  31525. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31526. // - uv is linear interpolation
  31527. //
  31528. // Topology is as below for sub-divide by 2
  31529. // vertex shown as v0,v1,v2
  31530. // interp index is i1 to progress in range [v0,v1[
  31531. // interp index is i2 to progress in range [v0,v2[
  31532. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31533. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31534. //
  31535. //
  31536. // i2 v2
  31537. // ^ ^
  31538. // / / \
  31539. // / / \
  31540. // / / \
  31541. // / / (0,1) \
  31542. // / #---------\
  31543. // / / \ (0,0)'/ \
  31544. // / / \ / \
  31545. // / / \ / \
  31546. // / / (0,0) \ / (1,0) \
  31547. // / #---------#---------\
  31548. // v0 v1
  31549. //
  31550. // --------------------> i1
  31551. //
  31552. // interp of (i1,i2):
  31553. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31554. // along i1 : lerp(x0,x1, i1/(S-i2))
  31555. //
  31556. // centroid of triangle is needed to get help normal computation
  31557. // (c1,c2) are used for centroid location
  31558. var interp_vertex = function (i1, i2, c1, c2) {
  31559. // vertex is interpolated from
  31560. // - face_vertex_pos[0..2]
  31561. // - face_vertex_uv[0..2]
  31562. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31563. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31564. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31565. pos_interp.normalize();
  31566. var vertex_normal;
  31567. if (flat) {
  31568. // in flat mode, recalculate normal as face centroid normal
  31569. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31570. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31571. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31572. }
  31573. else {
  31574. // in smooth mode, recalculate normal from each single vertex position
  31575. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31576. }
  31577. // Vertex normal need correction due to X,Y,Z radius scaling
  31578. vertex_normal.x /= radiusX;
  31579. vertex_normal.y /= radiusY;
  31580. vertex_normal.z /= radiusZ;
  31581. vertex_normal.normalize();
  31582. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31583. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31584. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31585. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31586. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31587. uvs.push(uv_interp.x, uv_interp.y);
  31588. // push each vertex has member of a face
  31589. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31590. indices.push(current_indice);
  31591. current_indice++;
  31592. };
  31593. for (var i2 = 0; i2 < subdivisions; i2++) {
  31594. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31595. // face : (i1,i2) for /\ :
  31596. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31597. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31598. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31599. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31600. if (i1 + i2 + 1 < subdivisions) {
  31601. // face : (i1,i2)' for \/ :
  31602. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31603. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31604. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31605. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31606. }
  31607. }
  31608. }
  31609. }
  31610. // Sides
  31611. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31612. // Result
  31613. var vertexData = new VertexData();
  31614. vertexData.indices = indices;
  31615. vertexData.positions = positions;
  31616. vertexData.normals = normals;
  31617. vertexData.uvs = uvs;
  31618. return vertexData;
  31619. };
  31620. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31621. /**
  31622. * Creates the VertexData of the Polyhedron.
  31623. */
  31624. VertexData.CreatePolyhedron = function (options) {
  31625. // provided polyhedron types :
  31626. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31627. // 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)
  31628. var polyhedra = [];
  31629. 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]] };
  31630. 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]] };
  31631. polyhedra[2] = {
  31632. 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]],
  31633. 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]]
  31634. };
  31635. polyhedra[3] = {
  31636. 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]],
  31637. 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]]
  31638. };
  31639. polyhedra[4] = {
  31640. 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]],
  31641. 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]]
  31642. };
  31643. 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]] };
  31644. 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]] };
  31645. 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]] };
  31646. 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]] };
  31647. 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]] };
  31648. 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]] };
  31649. 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]] };
  31650. 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]] };
  31651. 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]] };
  31652. polyhedra[14] = {
  31653. 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]],
  31654. 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]]
  31655. };
  31656. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31657. var size = options.size;
  31658. var sizeX = options.sizeX || size || 1;
  31659. var sizeY = options.sizeY || size || 1;
  31660. var sizeZ = options.sizeZ || size || 1;
  31661. var data = options.custom || polyhedra[type];
  31662. var nbfaces = data.face.length;
  31663. var faceUV = options.faceUV || new Array(nbfaces);
  31664. var faceColors = options.faceColors;
  31665. var flat = (options.flat === undefined) ? true : options.flat;
  31666. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31667. var positions = new Array();
  31668. var indices = new Array();
  31669. var normals = new Array();
  31670. var uvs = new Array();
  31671. var colors = new Array();
  31672. var index = 0;
  31673. var faceIdx = 0; // face cursor in the array "indexes"
  31674. var indexes = new Array();
  31675. var i = 0;
  31676. var f = 0;
  31677. var u, v, ang, x, y, tmp;
  31678. // default face colors and UV if undefined
  31679. if (flat) {
  31680. for (f = 0; f < nbfaces; f++) {
  31681. if (faceColors && faceColors[f] === undefined) {
  31682. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31683. }
  31684. if (faceUV && faceUV[f] === undefined) {
  31685. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31686. }
  31687. }
  31688. }
  31689. if (!flat) {
  31690. for (i = 0; i < data.vertex.length; i++) {
  31691. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31692. uvs.push(0, 0);
  31693. }
  31694. for (f = 0; f < nbfaces; f++) {
  31695. for (i = 0; i < data.face[f].length - 2; i++) {
  31696. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31697. }
  31698. }
  31699. }
  31700. else {
  31701. for (f = 0; f < nbfaces; f++) {
  31702. var fl = data.face[f].length; // number of vertices of the current face
  31703. ang = 2 * Math.PI / fl;
  31704. x = 0.5 * Math.tan(ang / 2);
  31705. y = 0.5;
  31706. // positions, uvs, colors
  31707. for (i = 0; i < fl; i++) {
  31708. // positions
  31709. 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);
  31710. indexes.push(index);
  31711. index++;
  31712. // uvs
  31713. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31714. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31715. uvs.push(u, v);
  31716. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31717. y = x * Math.sin(ang) + y * Math.cos(ang);
  31718. x = tmp;
  31719. // colors
  31720. if (faceColors) {
  31721. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31722. }
  31723. }
  31724. // indices from indexes
  31725. for (i = 0; i < fl - 2; i++) {
  31726. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31727. }
  31728. faceIdx += fl;
  31729. }
  31730. }
  31731. VertexData.ComputeNormals(positions, indices, normals);
  31732. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31733. var vertexData = new VertexData();
  31734. vertexData.positions = positions;
  31735. vertexData.indices = indices;
  31736. vertexData.normals = normals;
  31737. vertexData.uvs = uvs;
  31738. if (faceColors && flat) {
  31739. vertexData.colors = colors;
  31740. }
  31741. return vertexData;
  31742. };
  31743. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31744. /**
  31745. * Creates the VertexData of the Torus Knot.
  31746. */
  31747. VertexData.CreateTorusKnot = function (options) {
  31748. var indices = new Array();
  31749. var positions = new Array();
  31750. var normals = new Array();
  31751. var uvs = new Array();
  31752. var radius = options.radius || 2;
  31753. var tube = options.tube || 0.5;
  31754. var radialSegments = options.radialSegments || 32;
  31755. var tubularSegments = options.tubularSegments || 32;
  31756. var p = options.p || 2;
  31757. var q = options.q || 3;
  31758. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31759. // Helper
  31760. var getPos = function (angle) {
  31761. var cu = Math.cos(angle);
  31762. var su = Math.sin(angle);
  31763. var quOverP = q / p * angle;
  31764. var cs = Math.cos(quOverP);
  31765. var tx = radius * (2 + cs) * 0.5 * cu;
  31766. var ty = radius * (2 + cs) * su * 0.5;
  31767. var tz = radius * Math.sin(quOverP) * 0.5;
  31768. return new BABYLON.Vector3(tx, ty, tz);
  31769. };
  31770. // Vertices
  31771. var i;
  31772. var j;
  31773. for (i = 0; i <= radialSegments; i++) {
  31774. var modI = i % radialSegments;
  31775. var u = modI / radialSegments * 2 * p * Math.PI;
  31776. var p1 = getPos(u);
  31777. var p2 = getPos(u + 0.01);
  31778. var tang = p2.subtract(p1);
  31779. var n = p2.add(p1);
  31780. var bitan = BABYLON.Vector3.Cross(tang, n);
  31781. n = BABYLON.Vector3.Cross(bitan, tang);
  31782. bitan.normalize();
  31783. n.normalize();
  31784. for (j = 0; j < tubularSegments; j++) {
  31785. var modJ = j % tubularSegments;
  31786. var v = modJ / tubularSegments * 2 * Math.PI;
  31787. var cx = -tube * Math.cos(v);
  31788. var cy = tube * Math.sin(v);
  31789. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31790. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31791. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31792. uvs.push(i / radialSegments);
  31793. uvs.push(j / tubularSegments);
  31794. }
  31795. }
  31796. for (i = 0; i < radialSegments; i++) {
  31797. for (j = 0; j < tubularSegments; j++) {
  31798. var jNext = (j + 1) % tubularSegments;
  31799. var a = i * tubularSegments + j;
  31800. var b = (i + 1) * tubularSegments + j;
  31801. var c = (i + 1) * tubularSegments + jNext;
  31802. var d = i * tubularSegments + jNext;
  31803. indices.push(d);
  31804. indices.push(b);
  31805. indices.push(a);
  31806. indices.push(d);
  31807. indices.push(c);
  31808. indices.push(b);
  31809. }
  31810. }
  31811. // Normals
  31812. VertexData.ComputeNormals(positions, indices, normals);
  31813. // Sides
  31814. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31815. // Result
  31816. var vertexData = new VertexData();
  31817. vertexData.indices = indices;
  31818. vertexData.positions = positions;
  31819. vertexData.normals = normals;
  31820. vertexData.uvs = uvs;
  31821. return vertexData;
  31822. };
  31823. // Tools
  31824. /**
  31825. * @param {any} - positions (number[] or Float32Array)
  31826. * @param {any} - indices (number[] or Uint16Array)
  31827. * @param {any} - normals (number[] or Float32Array)
  31828. * options (optional) :
  31829. * facetPositions : optional array of facet positions (vector3)
  31830. * facetNormals : optional array of facet normals (vector3)
  31831. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31832. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31833. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31834. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31835. * bInfo : optional bounding info, required for facetPartitioning computation
  31836. * useRightHandedSystem: optional boolean to for right handed system computation
  31837. * depthSort : optional boolean to enable the facet depth sort computation
  31838. * distanceTo : optional Vector3 to compute the facet depth from this location
  31839. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31840. */
  31841. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31842. // temporary scalar variables
  31843. var index = 0; // facet index
  31844. var p1p2x = 0.0; // p1p2 vector x coordinate
  31845. var p1p2y = 0.0; // p1p2 vector y coordinate
  31846. var p1p2z = 0.0; // p1p2 vector z coordinate
  31847. var p3p2x = 0.0; // p3p2 vector x coordinate
  31848. var p3p2y = 0.0; // p3p2 vector y coordinate
  31849. var p3p2z = 0.0; // p3p2 vector z coordinate
  31850. var faceNormalx = 0.0; // facet normal x coordinate
  31851. var faceNormaly = 0.0; // facet normal y coordinate
  31852. var faceNormalz = 0.0; // facet normal z coordinate
  31853. var length = 0.0; // facet normal length before normalization
  31854. var v1x = 0; // vector1 x index in the positions array
  31855. var v1y = 0; // vector1 y index in the positions array
  31856. var v1z = 0; // vector1 z index in the positions array
  31857. var v2x = 0; // vector2 x index in the positions array
  31858. var v2y = 0; // vector2 y index in the positions array
  31859. var v2z = 0; // vector2 z index in the positions array
  31860. var v3x = 0; // vector3 x index in the positions array
  31861. var v3y = 0; // vector3 y index in the positions array
  31862. var v3z = 0; // vector3 z index in the positions array
  31863. var computeFacetNormals = false;
  31864. var computeFacetPositions = false;
  31865. var computeFacetPartitioning = false;
  31866. var computeDepthSort = false;
  31867. var faceNormalSign = 1;
  31868. var ratio = 0;
  31869. var distanceTo = null;
  31870. if (options) {
  31871. computeFacetNormals = (options.facetNormals) ? true : false;
  31872. computeFacetPositions = (options.facetPositions) ? true : false;
  31873. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31874. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31875. ratio = options.ratio || 0;
  31876. computeDepthSort = (options.depthSort) ? true : false;
  31877. distanceTo = (options.distanceTo);
  31878. if (computeDepthSort) {
  31879. if (distanceTo === undefined) {
  31880. distanceTo = BABYLON.Vector3.Zero();
  31881. }
  31882. var depthSortedFacets = options.depthSortedFacets;
  31883. }
  31884. }
  31885. // facetPartitioning reinit if needed
  31886. var xSubRatio = 0;
  31887. var ySubRatio = 0;
  31888. var zSubRatio = 0;
  31889. var subSq = 0;
  31890. if (computeFacetPartitioning && options && options.bbSize) {
  31891. var ox = 0; // X partitioning index for facet position
  31892. var oy = 0; // Y partinioning index for facet position
  31893. var oz = 0; // Z partinioning index for facet position
  31894. var b1x = 0; // X partitioning index for facet v1 vertex
  31895. var b1y = 0; // Y partitioning index for facet v1 vertex
  31896. var b1z = 0; // z partitioning index for facet v1 vertex
  31897. var b2x = 0; // X partitioning index for facet v2 vertex
  31898. var b2y = 0; // Y partitioning index for facet v2 vertex
  31899. var b2z = 0; // Z partitioning index for facet v2 vertex
  31900. var b3x = 0; // X partitioning index for facet v3 vertex
  31901. var b3y = 0; // Y partitioning index for facet v3 vertex
  31902. var b3z = 0; // Z partitioning index for facet v3 vertex
  31903. var block_idx_o = 0; // facet barycenter block index
  31904. var block_idx_v1 = 0; // v1 vertex block index
  31905. var block_idx_v2 = 0; // v2 vertex block index
  31906. var block_idx_v3 = 0; // v3 vertex block index
  31907. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31908. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31909. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31910. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31911. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31912. subSq = options.subDiv.max * options.subDiv.max;
  31913. options.facetPartitioning.length = 0;
  31914. }
  31915. // reset the normals
  31916. for (index = 0; index < positions.length; index++) {
  31917. normals[index] = 0.0;
  31918. }
  31919. // Loop : 1 indice triplet = 1 facet
  31920. var nbFaces = (indices.length / 3) | 0;
  31921. for (index = 0; index < nbFaces; index++) {
  31922. // get the indexes of the coordinates of each vertex of the facet
  31923. v1x = indices[index * 3] * 3;
  31924. v1y = v1x + 1;
  31925. v1z = v1x + 2;
  31926. v2x = indices[index * 3 + 1] * 3;
  31927. v2y = v2x + 1;
  31928. v2z = v2x + 2;
  31929. v3x = indices[index * 3 + 2] * 3;
  31930. v3y = v3x + 1;
  31931. v3z = v3x + 2;
  31932. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31933. p1p2y = positions[v1y] - positions[v2y];
  31934. p1p2z = positions[v1z] - positions[v2z];
  31935. p3p2x = positions[v3x] - positions[v2x];
  31936. p3p2y = positions[v3y] - positions[v2y];
  31937. p3p2z = positions[v3z] - positions[v2z];
  31938. // compute the face normal with the cross product
  31939. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31940. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31941. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31942. // normalize this normal and store it in the array facetData
  31943. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31944. length = (length === 0) ? 1.0 : length;
  31945. faceNormalx /= length;
  31946. faceNormaly /= length;
  31947. faceNormalz /= length;
  31948. if (computeFacetNormals && options) {
  31949. options.facetNormals[index].x = faceNormalx;
  31950. options.facetNormals[index].y = faceNormaly;
  31951. options.facetNormals[index].z = faceNormalz;
  31952. }
  31953. if (computeFacetPositions && options) {
  31954. // compute and the facet barycenter coordinates in the array facetPositions
  31955. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31956. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31957. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31958. }
  31959. if (computeFacetPartitioning && options) {
  31960. // store the facet indexes in arrays in the main facetPartitioning array :
  31961. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31962. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31963. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31964. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31965. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31966. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31967. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31968. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31969. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31970. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31971. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31972. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31973. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31974. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31975. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31976. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31977. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31978. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31979. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31980. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31981. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31982. // push each facet index in each block containing the vertex
  31983. options.facetPartitioning[block_idx_v1].push(index);
  31984. if (block_idx_v2 != block_idx_v1) {
  31985. options.facetPartitioning[block_idx_v2].push(index);
  31986. }
  31987. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31988. options.facetPartitioning[block_idx_v3].push(index);
  31989. }
  31990. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31991. options.facetPartitioning[block_idx_o].push(index);
  31992. }
  31993. }
  31994. if (computeDepthSort && options && options.facetPositions) {
  31995. var dsf = depthSortedFacets[index];
  31996. dsf.ind = index * 3;
  31997. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31998. }
  31999. // compute the normals anyway
  32000. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32001. normals[v1y] += faceNormaly;
  32002. normals[v1z] += faceNormalz;
  32003. normals[v2x] += faceNormalx;
  32004. normals[v2y] += faceNormaly;
  32005. normals[v2z] += faceNormalz;
  32006. normals[v3x] += faceNormalx;
  32007. normals[v3y] += faceNormaly;
  32008. normals[v3z] += faceNormalz;
  32009. }
  32010. // last normalization of each normal
  32011. for (index = 0; index < normals.length / 3; index++) {
  32012. faceNormalx = normals[index * 3];
  32013. faceNormaly = normals[index * 3 + 1];
  32014. faceNormalz = normals[index * 3 + 2];
  32015. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32016. length = (length === 0) ? 1.0 : length;
  32017. faceNormalx /= length;
  32018. faceNormaly /= length;
  32019. faceNormalz /= length;
  32020. normals[index * 3] = faceNormalx;
  32021. normals[index * 3 + 1] = faceNormaly;
  32022. normals[index * 3 + 2] = faceNormalz;
  32023. }
  32024. };
  32025. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32026. var li = indices.length;
  32027. var ln = normals.length;
  32028. var i;
  32029. var n;
  32030. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32031. switch (sideOrientation) {
  32032. case BABYLON.Mesh.FRONTSIDE:
  32033. // nothing changed
  32034. break;
  32035. case BABYLON.Mesh.BACKSIDE:
  32036. var tmp;
  32037. // indices
  32038. for (i = 0; i < li; i += 3) {
  32039. tmp = indices[i];
  32040. indices[i] = indices[i + 2];
  32041. indices[i + 2] = tmp;
  32042. }
  32043. // normals
  32044. for (n = 0; n < ln; n++) {
  32045. normals[n] = -normals[n];
  32046. }
  32047. break;
  32048. case BABYLON.Mesh.DOUBLESIDE:
  32049. // positions
  32050. var lp = positions.length;
  32051. var l = lp / 3;
  32052. for (var p = 0; p < lp; p++) {
  32053. positions[lp + p] = positions[p];
  32054. }
  32055. // indices
  32056. for (i = 0; i < li; i += 3) {
  32057. indices[i + li] = indices[i + 2] + l;
  32058. indices[i + 1 + li] = indices[i + 1] + l;
  32059. indices[i + 2 + li] = indices[i] + l;
  32060. }
  32061. // normals
  32062. for (n = 0; n < ln; n++) {
  32063. normals[ln + n] = -normals[n];
  32064. }
  32065. // uvs
  32066. var lu = uvs.length;
  32067. var u = 0;
  32068. for (u = 0; u < lu; u++) {
  32069. uvs[u + lu] = uvs[u];
  32070. }
  32071. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32072. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32073. u = 0;
  32074. for (i = 0; i < lu / 2; i++) {
  32075. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32076. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32077. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32078. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32079. u += 2;
  32080. }
  32081. break;
  32082. }
  32083. };
  32084. /**
  32085. * Creates a new VertexData from the imported parameters.
  32086. */
  32087. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32088. var vertexData = new VertexData();
  32089. // positions
  32090. var positions = parsedVertexData.positions;
  32091. if (positions) {
  32092. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32093. }
  32094. // normals
  32095. var normals = parsedVertexData.normals;
  32096. if (normals) {
  32097. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32098. }
  32099. // tangents
  32100. var tangents = parsedVertexData.tangents;
  32101. if (tangents) {
  32102. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32103. }
  32104. // uvs
  32105. var uvs = parsedVertexData.uvs;
  32106. if (uvs) {
  32107. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32108. }
  32109. // uv2s
  32110. var uv2s = parsedVertexData.uv2s;
  32111. if (uv2s) {
  32112. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32113. }
  32114. // uv3s
  32115. var uv3s = parsedVertexData.uv3s;
  32116. if (uv3s) {
  32117. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32118. }
  32119. // uv4s
  32120. var uv4s = parsedVertexData.uv4s;
  32121. if (uv4s) {
  32122. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32123. }
  32124. // uv5s
  32125. var uv5s = parsedVertexData.uv5s;
  32126. if (uv5s) {
  32127. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32128. }
  32129. // uv6s
  32130. var uv6s = parsedVertexData.uv6s;
  32131. if (uv6s) {
  32132. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32133. }
  32134. // colors
  32135. var colors = parsedVertexData.colors;
  32136. if (colors) {
  32137. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32138. }
  32139. // matricesIndices
  32140. var matricesIndices = parsedVertexData.matricesIndices;
  32141. if (matricesIndices) {
  32142. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32143. }
  32144. // matricesWeights
  32145. var matricesWeights = parsedVertexData.matricesWeights;
  32146. if (matricesWeights) {
  32147. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32148. }
  32149. // indices
  32150. var indices = parsedVertexData.indices;
  32151. if (indices) {
  32152. vertexData.indices = indices;
  32153. }
  32154. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32155. };
  32156. return VertexData;
  32157. }());
  32158. BABYLON.VertexData = VertexData;
  32159. })(BABYLON || (BABYLON = {}));
  32160. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32161. var BABYLON;
  32162. (function (BABYLON) {
  32163. /**
  32164. * Class used to store geometry data (vertex buffers + index buffer)
  32165. */
  32166. var Geometry = /** @class */ (function () {
  32167. /**
  32168. * Creates a new geometry
  32169. * @param id defines the unique ID
  32170. * @param scene defines the hosting scene
  32171. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32172. * @param updatable defines if geometry must be updatable (false by default)
  32173. * @param mesh defines the mesh that will be associated with the geometry
  32174. */
  32175. function Geometry(id, scene, vertexData, updatable, mesh) {
  32176. if (updatable === void 0) { updatable = false; }
  32177. if (mesh === void 0) { mesh = null; }
  32178. /**
  32179. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32180. */
  32181. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32182. this._totalVertices = 0;
  32183. this._isDisposed = false;
  32184. this._indexBufferIsUpdatable = false;
  32185. this.id = id;
  32186. this._engine = scene.getEngine();
  32187. this._meshes = [];
  32188. this._scene = scene;
  32189. //Init vertex buffer cache
  32190. this._vertexBuffers = {};
  32191. this._indices = [];
  32192. this._updatable = updatable;
  32193. // vertexData
  32194. if (vertexData) {
  32195. this.setAllVerticesData(vertexData, updatable);
  32196. }
  32197. else {
  32198. this._totalVertices = 0;
  32199. this._indices = [];
  32200. }
  32201. if (this._engine.getCaps().vertexArrayObject) {
  32202. this._vertexArrayObjects = {};
  32203. }
  32204. // applyToMesh
  32205. if (mesh) {
  32206. if (mesh.getClassName() === "LinesMesh") {
  32207. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32208. this.updateExtend();
  32209. }
  32210. this.applyToMesh(mesh);
  32211. mesh.computeWorldMatrix(true);
  32212. }
  32213. }
  32214. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32215. /**
  32216. * 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
  32217. */
  32218. get: function () {
  32219. return this._boundingBias;
  32220. },
  32221. /**
  32222. * 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
  32223. */
  32224. set: function (value) {
  32225. if (this._boundingBias && this._boundingBias.equals(value)) {
  32226. return;
  32227. }
  32228. this._boundingBias = value.clone();
  32229. this.updateBoundingInfo(true, null);
  32230. },
  32231. enumerable: true,
  32232. configurable: true
  32233. });
  32234. /**
  32235. * Static function used to attach a new empty geometry to a mesh
  32236. * @param mesh defines the mesh to attach the geometry to
  32237. * @returns the new {BABYLON.Geometry}
  32238. */
  32239. Geometry.CreateGeometryForMesh = function (mesh) {
  32240. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32241. geometry.applyToMesh(mesh);
  32242. return geometry;
  32243. };
  32244. Object.defineProperty(Geometry.prototype, "extend", {
  32245. /**
  32246. * Gets the current extend of the geometry
  32247. */
  32248. get: function () {
  32249. return this._extend;
  32250. },
  32251. enumerable: true,
  32252. configurable: true
  32253. });
  32254. /**
  32255. * Gets the hosting scene
  32256. * @returns the hosting {BABYLON.Scene}
  32257. */
  32258. Geometry.prototype.getScene = function () {
  32259. return this._scene;
  32260. };
  32261. /**
  32262. * Gets the hosting engine
  32263. * @returns the hosting {BABYLON.Engine}
  32264. */
  32265. Geometry.prototype.getEngine = function () {
  32266. return this._engine;
  32267. };
  32268. /**
  32269. * Defines if the geometry is ready to use
  32270. * @returns true if the geometry is ready to be used
  32271. */
  32272. Geometry.prototype.isReady = function () {
  32273. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32274. };
  32275. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32276. /**
  32277. * Gets a value indicating that the geometry should not be serialized
  32278. */
  32279. get: function () {
  32280. for (var index = 0; index < this._meshes.length; index++) {
  32281. if (!this._meshes[index].doNotSerialize) {
  32282. return false;
  32283. }
  32284. }
  32285. return true;
  32286. },
  32287. enumerable: true,
  32288. configurable: true
  32289. });
  32290. /** @ignore */
  32291. Geometry.prototype._rebuild = function () {
  32292. if (this._vertexArrayObjects) {
  32293. this._vertexArrayObjects = {};
  32294. }
  32295. // Index buffer
  32296. if (this._meshes.length !== 0 && this._indices) {
  32297. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32298. }
  32299. // Vertex buffers
  32300. for (var key in this._vertexBuffers) {
  32301. var vertexBuffer = this._vertexBuffers[key];
  32302. vertexBuffer._rebuild();
  32303. }
  32304. };
  32305. /**
  32306. * Affects all gemetry data in one call
  32307. * @param vertexData defines the geometry data
  32308. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32309. */
  32310. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32311. vertexData.applyToGeometry(this, updatable);
  32312. this.notifyUpdate();
  32313. };
  32314. /**
  32315. * Set specific vertex data
  32316. * @param kind defines the data kind (Position, normal, etc...)
  32317. * @param data defines the vertex data to use
  32318. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32319. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32320. */
  32321. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32322. if (updatable === void 0) { updatable = false; }
  32323. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32324. this.setVerticesBuffer(buffer);
  32325. };
  32326. /**
  32327. * Removes a specific vertex data
  32328. * @param kind defines the data kind (Position, normal, etc...)
  32329. */
  32330. Geometry.prototype.removeVerticesData = function (kind) {
  32331. if (this._vertexBuffers[kind]) {
  32332. this._vertexBuffers[kind].dispose();
  32333. delete this._vertexBuffers[kind];
  32334. }
  32335. };
  32336. /**
  32337. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32338. * @param buffer defines the vertex buffer to use
  32339. */
  32340. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32341. var kind = buffer.getKind();
  32342. if (this._vertexBuffers[kind]) {
  32343. this._vertexBuffers[kind].dispose();
  32344. }
  32345. this._vertexBuffers[kind] = buffer;
  32346. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32347. var data = buffer.getData();
  32348. var stride = buffer.getStrideSize();
  32349. this._totalVertices = data.length / stride;
  32350. this.updateExtend(data, stride);
  32351. this._resetPointsArrayCache();
  32352. var meshes = this._meshes;
  32353. var numOfMeshes = meshes.length;
  32354. for (var index = 0; index < numOfMeshes; index++) {
  32355. var mesh = meshes[index];
  32356. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32357. mesh._createGlobalSubMesh(false);
  32358. mesh.computeWorldMatrix(true);
  32359. }
  32360. }
  32361. this.notifyUpdate(kind);
  32362. if (this._vertexArrayObjects) {
  32363. this._disposeVertexArrayObjects();
  32364. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32365. }
  32366. };
  32367. /**
  32368. * Update a specific vertex buffer
  32369. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32370. * It will do nothing if the buffer is not updatable
  32371. * @param kind defines the data kind (Position, normal, etc...)
  32372. * @param data defines the data to use
  32373. * @param offset defines the offset in the target buffer where to store the data
  32374. */
  32375. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32376. var vertexBuffer = this.getVertexBuffer(kind);
  32377. if (!vertexBuffer) {
  32378. return;
  32379. }
  32380. vertexBuffer.updateDirectly(data, offset);
  32381. this.notifyUpdate(kind);
  32382. };
  32383. /**
  32384. * Update a specific vertex buffer
  32385. * This function will create a new buffer if the current one is not updatable
  32386. * @param kind defines the data kind (Position, normal, etc...)
  32387. * @param data defines the data to use
  32388. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32389. */
  32390. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32391. if (updateExtends === void 0) { updateExtends = false; }
  32392. var vertexBuffer = this.getVertexBuffer(kind);
  32393. if (!vertexBuffer) {
  32394. return;
  32395. }
  32396. vertexBuffer.update(data);
  32397. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32398. var stride = vertexBuffer.getStrideSize();
  32399. this._totalVertices = data.length / stride;
  32400. this.updateBoundingInfo(updateExtends, data);
  32401. }
  32402. this.notifyUpdate(kind);
  32403. };
  32404. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32405. if (updateExtends) {
  32406. this.updateExtend(data);
  32407. }
  32408. var meshes = this._meshes;
  32409. var numOfMeshes = meshes.length;
  32410. this._resetPointsArrayCache();
  32411. for (var index = 0; index < numOfMeshes; index++) {
  32412. var mesh = meshes[index];
  32413. if (updateExtends) {
  32414. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32415. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32416. var subMesh = mesh.subMeshes[subIndex];
  32417. subMesh.refreshBoundingInfo();
  32418. }
  32419. }
  32420. }
  32421. };
  32422. /** @ignore */
  32423. Geometry.prototype._bind = function (effect, indexToBind) {
  32424. if (!effect) {
  32425. return;
  32426. }
  32427. if (indexToBind === undefined) {
  32428. indexToBind = this._indexBuffer;
  32429. }
  32430. var vbs = this.getVertexBuffers();
  32431. if (!vbs) {
  32432. return;
  32433. }
  32434. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32435. this._engine.bindBuffers(vbs, indexToBind, effect);
  32436. return;
  32437. }
  32438. // Using VAO
  32439. if (!this._vertexArrayObjects[effect.key]) {
  32440. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32441. }
  32442. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32443. };
  32444. /**
  32445. * Gets total number of vertices
  32446. * @returns the total number of vertices
  32447. */
  32448. Geometry.prototype.getTotalVertices = function () {
  32449. if (!this.isReady()) {
  32450. return 0;
  32451. }
  32452. return this._totalVertices;
  32453. };
  32454. /**
  32455. * Gets a specific vertex data attached to this geometry
  32456. * @param kind defines the data kind (Position, normal, etc...)
  32457. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32458. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32459. * @returns a float array containing vertex data
  32460. */
  32461. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32462. var vertexBuffer = this.getVertexBuffer(kind);
  32463. if (!vertexBuffer) {
  32464. return null;
  32465. }
  32466. var orig = vertexBuffer.getData();
  32467. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32468. return orig;
  32469. }
  32470. else {
  32471. var len = orig.length;
  32472. var copy = [];
  32473. for (var i = 0; i < len; i++) {
  32474. copy.push(orig[i]);
  32475. }
  32476. return copy;
  32477. }
  32478. };
  32479. /**
  32480. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32481. * @param kind defines the data kind (Position, normal, etc...)
  32482. * @returns true if the vertex buffer with the specified kind is updatable
  32483. */
  32484. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32485. var vb = this._vertexBuffers[kind];
  32486. if (!vb) {
  32487. return false;
  32488. }
  32489. return vb.isUpdatable();
  32490. };
  32491. /**
  32492. * Gets a specific vertex buffer
  32493. * @param kind defines the data kind (Position, normal, etc...)
  32494. * @returns a {BABYLON.VertexBuffer}
  32495. */
  32496. Geometry.prototype.getVertexBuffer = function (kind) {
  32497. if (!this.isReady()) {
  32498. return null;
  32499. }
  32500. return this._vertexBuffers[kind];
  32501. };
  32502. /**
  32503. * Returns all vertex buffers
  32504. * @return an object holding all vertex buffers indexed by kind
  32505. */
  32506. Geometry.prototype.getVertexBuffers = function () {
  32507. if (!this.isReady()) {
  32508. return null;
  32509. }
  32510. return this._vertexBuffers;
  32511. };
  32512. /**
  32513. * Gets a boolean indicating if specific vertex buffer is present
  32514. * @param kind defines the data kind (Position, normal, etc...)
  32515. * @returns true if data is present
  32516. */
  32517. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32518. if (!this._vertexBuffers) {
  32519. if (this._delayInfo) {
  32520. return this._delayInfo.indexOf(kind) !== -1;
  32521. }
  32522. return false;
  32523. }
  32524. return this._vertexBuffers[kind] !== undefined;
  32525. };
  32526. /**
  32527. * Gets a list of all attached data kinds (Position, normal, etc...)
  32528. * @returns a list of string containing all kinds
  32529. */
  32530. Geometry.prototype.getVerticesDataKinds = function () {
  32531. var result = [];
  32532. var kind;
  32533. if (!this._vertexBuffers && this._delayInfo) {
  32534. for (kind in this._delayInfo) {
  32535. result.push(kind);
  32536. }
  32537. }
  32538. else {
  32539. for (kind in this._vertexBuffers) {
  32540. result.push(kind);
  32541. }
  32542. }
  32543. return result;
  32544. };
  32545. /**
  32546. * Update index buffer
  32547. * @param indices defines the indices to store in the index buffer
  32548. * @param offset defines the offset in the target buffer where to store the data
  32549. */
  32550. Geometry.prototype.updateIndices = function (indices, offset) {
  32551. if (!this._indexBuffer) {
  32552. return;
  32553. }
  32554. if (!this._indexBufferIsUpdatable) {
  32555. this.setIndices(indices, null, true);
  32556. }
  32557. else {
  32558. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32559. }
  32560. };
  32561. /**
  32562. * Creates a new index buffer
  32563. * @param indices defines the indices to store in the index buffer
  32564. * @param totalVertices defines the total number of vertices (could be null)
  32565. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32566. */
  32567. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32568. if (totalVertices === void 0) { totalVertices = null; }
  32569. if (updatable === void 0) { updatable = false; }
  32570. if (this._indexBuffer) {
  32571. this._engine._releaseBuffer(this._indexBuffer);
  32572. }
  32573. this._disposeVertexArrayObjects();
  32574. this._indices = indices;
  32575. this._indexBufferIsUpdatable = updatable;
  32576. if (this._meshes.length !== 0 && this._indices) {
  32577. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32578. }
  32579. if (totalVertices != undefined) {
  32580. this._totalVertices = totalVertices;
  32581. }
  32582. var meshes = this._meshes;
  32583. var numOfMeshes = meshes.length;
  32584. for (var index = 0; index < numOfMeshes; index++) {
  32585. meshes[index]._createGlobalSubMesh(true);
  32586. }
  32587. this.notifyUpdate();
  32588. };
  32589. /**
  32590. * Return the total number of indices
  32591. * @returns the total number of indices
  32592. */
  32593. Geometry.prototype.getTotalIndices = function () {
  32594. if (!this.isReady()) {
  32595. return 0;
  32596. }
  32597. return this._indices.length;
  32598. };
  32599. /**
  32600. * Gets the index buffer array
  32601. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32602. * @returns the index buffer array
  32603. */
  32604. Geometry.prototype.getIndices = function (copyWhenShared) {
  32605. if (!this.isReady()) {
  32606. return null;
  32607. }
  32608. var orig = this._indices;
  32609. if (!copyWhenShared || this._meshes.length === 1) {
  32610. return orig;
  32611. }
  32612. else {
  32613. var len = orig.length;
  32614. var copy = [];
  32615. for (var i = 0; i < len; i++) {
  32616. copy.push(orig[i]);
  32617. }
  32618. return copy;
  32619. }
  32620. };
  32621. /**
  32622. * Gets the index buffer
  32623. * @return the index buffer
  32624. */
  32625. Geometry.prototype.getIndexBuffer = function () {
  32626. if (!this.isReady()) {
  32627. return null;
  32628. }
  32629. return this._indexBuffer;
  32630. };
  32631. /** @ignore */
  32632. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32633. if (effect === void 0) { effect = null; }
  32634. if (!effect || !this._vertexArrayObjects) {
  32635. return;
  32636. }
  32637. if (this._vertexArrayObjects[effect.key]) {
  32638. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32639. delete this._vertexArrayObjects[effect.key];
  32640. }
  32641. };
  32642. /**
  32643. * Release the associated resources for a specific mesh
  32644. * @param mesh defines the source mesh
  32645. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32646. */
  32647. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32648. var meshes = this._meshes;
  32649. var index = meshes.indexOf(mesh);
  32650. if (index === -1) {
  32651. return;
  32652. }
  32653. meshes.splice(index, 1);
  32654. mesh._geometry = null;
  32655. if (meshes.length === 0 && shouldDispose) {
  32656. this.dispose();
  32657. }
  32658. };
  32659. /**
  32660. * Apply current geometry to a given mesh
  32661. * @param mesh defines the mesh to apply geometry to
  32662. */
  32663. Geometry.prototype.applyToMesh = function (mesh) {
  32664. if (mesh._geometry === this) {
  32665. return;
  32666. }
  32667. var previousGeometry = mesh._geometry;
  32668. if (previousGeometry) {
  32669. previousGeometry.releaseForMesh(mesh);
  32670. }
  32671. var meshes = this._meshes;
  32672. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32673. mesh._geometry = this;
  32674. this._scene.pushGeometry(this);
  32675. meshes.push(mesh);
  32676. if (this.isReady()) {
  32677. this._applyToMesh(mesh);
  32678. }
  32679. else {
  32680. mesh._boundingInfo = this._boundingInfo;
  32681. }
  32682. };
  32683. Geometry.prototype.updateExtend = function (data, stride) {
  32684. if (data === void 0) { data = null; }
  32685. if (!data) {
  32686. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32687. }
  32688. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32689. };
  32690. Geometry.prototype._applyToMesh = function (mesh) {
  32691. var numOfMeshes = this._meshes.length;
  32692. // vertexBuffers
  32693. for (var kind in this._vertexBuffers) {
  32694. if (numOfMeshes === 1) {
  32695. this._vertexBuffers[kind].create();
  32696. }
  32697. var buffer = this._vertexBuffers[kind].getBuffer();
  32698. if (buffer)
  32699. buffer.references = numOfMeshes;
  32700. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32701. if (!this._extend) {
  32702. this.updateExtend(this._vertexBuffers[kind].getData());
  32703. }
  32704. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32705. mesh._createGlobalSubMesh(false);
  32706. //bounding info was just created again, world matrix should be applied again.
  32707. mesh._updateBoundingInfo();
  32708. }
  32709. }
  32710. // indexBuffer
  32711. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32712. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32713. }
  32714. if (this._indexBuffer) {
  32715. this._indexBuffer.references = numOfMeshes;
  32716. }
  32717. };
  32718. Geometry.prototype.notifyUpdate = function (kind) {
  32719. if (this.onGeometryUpdated) {
  32720. this.onGeometryUpdated(this, kind);
  32721. }
  32722. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32723. var mesh = _a[_i];
  32724. mesh._markSubMeshesAsAttributesDirty();
  32725. }
  32726. };
  32727. /**
  32728. * Load the geometry if it was flagged as delay loaded
  32729. * @param scene defines the hosting scene
  32730. * @param onLoaded defines a callback called when the geometry is loaded
  32731. */
  32732. Geometry.prototype.load = function (scene, onLoaded) {
  32733. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32734. return;
  32735. }
  32736. if (this.isReady()) {
  32737. if (onLoaded) {
  32738. onLoaded();
  32739. }
  32740. return;
  32741. }
  32742. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32743. this._queueLoad(scene, onLoaded);
  32744. };
  32745. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32746. var _this = this;
  32747. if (!this.delayLoadingFile) {
  32748. return;
  32749. }
  32750. scene._addPendingData(this);
  32751. scene._loadFile(this.delayLoadingFile, function (data) {
  32752. if (!_this._delayLoadingFunction) {
  32753. return;
  32754. }
  32755. _this._delayLoadingFunction(JSON.parse(data), _this);
  32756. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32757. _this._delayInfo = [];
  32758. scene._removePendingData(_this);
  32759. var meshes = _this._meshes;
  32760. var numOfMeshes = meshes.length;
  32761. for (var index = 0; index < numOfMeshes; index++) {
  32762. _this._applyToMesh(meshes[index]);
  32763. }
  32764. if (onLoaded) {
  32765. onLoaded();
  32766. }
  32767. }, undefined, true);
  32768. };
  32769. /**
  32770. * Invert the geometry to move from a right handed system to a left handed one.
  32771. */
  32772. Geometry.prototype.toLeftHanded = function () {
  32773. // Flip faces
  32774. var tIndices = this.getIndices(false);
  32775. if (tIndices != null && tIndices.length > 0) {
  32776. for (var i = 0; i < tIndices.length; i += 3) {
  32777. var tTemp = tIndices[i + 0];
  32778. tIndices[i + 0] = tIndices[i + 2];
  32779. tIndices[i + 2] = tTemp;
  32780. }
  32781. this.setIndices(tIndices);
  32782. }
  32783. // Negate position.z
  32784. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32785. if (tPositions != null && tPositions.length > 0) {
  32786. for (var i = 0; i < tPositions.length; i += 3) {
  32787. tPositions[i + 2] = -tPositions[i + 2];
  32788. }
  32789. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32790. }
  32791. // Negate normal.z
  32792. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32793. if (tNormals != null && tNormals.length > 0) {
  32794. for (var i = 0; i < tNormals.length; i += 3) {
  32795. tNormals[i + 2] = -tNormals[i + 2];
  32796. }
  32797. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32798. }
  32799. };
  32800. // Cache
  32801. /** @ignore */
  32802. Geometry.prototype._resetPointsArrayCache = function () {
  32803. this._positions = null;
  32804. };
  32805. /** @ignore */
  32806. Geometry.prototype._generatePointsArray = function () {
  32807. if (this._positions)
  32808. return true;
  32809. this._positions = [];
  32810. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32811. if (!data) {
  32812. return false;
  32813. }
  32814. for (var index = 0; index < data.length; index += 3) {
  32815. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32816. }
  32817. return true;
  32818. };
  32819. /**
  32820. * Gets a value indicating if the geometry is disposed
  32821. * @returns true if the geometry was disposed
  32822. */
  32823. Geometry.prototype.isDisposed = function () {
  32824. return this._isDisposed;
  32825. };
  32826. Geometry.prototype._disposeVertexArrayObjects = function () {
  32827. if (this._vertexArrayObjects) {
  32828. for (var kind in this._vertexArrayObjects) {
  32829. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32830. }
  32831. this._vertexArrayObjects = {};
  32832. }
  32833. };
  32834. /**
  32835. * Free all associated resources
  32836. */
  32837. Geometry.prototype.dispose = function () {
  32838. var meshes = this._meshes;
  32839. var numOfMeshes = meshes.length;
  32840. var index;
  32841. for (index = 0; index < numOfMeshes; index++) {
  32842. this.releaseForMesh(meshes[index]);
  32843. }
  32844. this._meshes = [];
  32845. this._disposeVertexArrayObjects();
  32846. for (var kind in this._vertexBuffers) {
  32847. this._vertexBuffers[kind].dispose();
  32848. }
  32849. this._vertexBuffers = {};
  32850. this._totalVertices = 0;
  32851. if (this._indexBuffer) {
  32852. this._engine._releaseBuffer(this._indexBuffer);
  32853. }
  32854. this._indexBuffer = null;
  32855. this._indices = [];
  32856. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32857. this.delayLoadingFile = null;
  32858. this._delayLoadingFunction = null;
  32859. this._delayInfo = [];
  32860. this._boundingInfo = null;
  32861. this._scene.removeGeometry(this);
  32862. this._isDisposed = true;
  32863. };
  32864. /**
  32865. * Clone the current geometry into a new geometry
  32866. * @param id defines the unique ID of the new geometry
  32867. * @returns a new geometry object
  32868. */
  32869. Geometry.prototype.copy = function (id) {
  32870. var vertexData = new BABYLON.VertexData();
  32871. vertexData.indices = [];
  32872. var indices = this.getIndices();
  32873. if (indices) {
  32874. for (var index = 0; index < indices.length; index++) {
  32875. vertexData.indices.push(indices[index]);
  32876. }
  32877. }
  32878. var updatable = false;
  32879. var stopChecking = false;
  32880. var kind;
  32881. for (kind in this._vertexBuffers) {
  32882. // using slice() to make a copy of the array and not just reference it
  32883. var data = this.getVerticesData(kind);
  32884. if (data instanceof Float32Array) {
  32885. vertexData.set(new Float32Array(data), kind);
  32886. }
  32887. else {
  32888. vertexData.set(data.slice(0), kind);
  32889. }
  32890. if (!stopChecking) {
  32891. var vb = this.getVertexBuffer(kind);
  32892. if (vb) {
  32893. updatable = vb.isUpdatable();
  32894. stopChecking = !updatable;
  32895. }
  32896. }
  32897. }
  32898. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32899. geometry.delayLoadState = this.delayLoadState;
  32900. geometry.delayLoadingFile = this.delayLoadingFile;
  32901. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32902. for (kind in this._delayInfo) {
  32903. geometry._delayInfo = geometry._delayInfo || [];
  32904. geometry._delayInfo.push(kind);
  32905. }
  32906. // Bounding info
  32907. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32908. return geometry;
  32909. };
  32910. /**
  32911. * Serialize the current geometry info (and not the vertices data) into a JSON object
  32912. * @return a JSON representation of the current geometry data (without the vertices data)
  32913. */
  32914. Geometry.prototype.serialize = function () {
  32915. var serializationObject = {};
  32916. serializationObject.id = this.id;
  32917. serializationObject.updatable = this._updatable;
  32918. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32919. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32920. }
  32921. return serializationObject;
  32922. };
  32923. Geometry.prototype.toNumberArray = function (origin) {
  32924. if (Array.isArray(origin)) {
  32925. return origin;
  32926. }
  32927. else {
  32928. return Array.prototype.slice.call(origin);
  32929. }
  32930. };
  32931. /**
  32932. * Serialize all vertices data into a JSON oject
  32933. * @returns a JSON representation of the current geometry data
  32934. */
  32935. Geometry.prototype.serializeVerticeData = function () {
  32936. var serializationObject = this.serialize();
  32937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32938. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32940. serializationObject.positions._updatable = true;
  32941. }
  32942. }
  32943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32944. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32946. serializationObject.normals._updatable = true;
  32947. }
  32948. }
  32949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32950. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  32951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  32952. serializationObject.tangets._updatable = true;
  32953. }
  32954. }
  32955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32956. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32958. serializationObject.uvs._updatable = true;
  32959. }
  32960. }
  32961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32962. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32963. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32964. serializationObject.uv2s._updatable = true;
  32965. }
  32966. }
  32967. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32968. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32969. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32970. serializationObject.uv3s._updatable = true;
  32971. }
  32972. }
  32973. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32974. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32975. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32976. serializationObject.uv4s._updatable = true;
  32977. }
  32978. }
  32979. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32980. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32981. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32982. serializationObject.uv5s._updatable = true;
  32983. }
  32984. }
  32985. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32986. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32987. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32988. serializationObject.uv6s._updatable = true;
  32989. }
  32990. }
  32991. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32992. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32993. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32994. serializationObject.colors._updatable = true;
  32995. }
  32996. }
  32997. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32998. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32999. serializationObject.matricesIndices._isExpanded = true;
  33000. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33001. serializationObject.matricesIndices._updatable = true;
  33002. }
  33003. }
  33004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33005. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33006. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33007. serializationObject.matricesWeights._updatable = true;
  33008. }
  33009. }
  33010. serializationObject.indices = this.toNumberArray(this.getIndices());
  33011. return serializationObject;
  33012. };
  33013. // Statics
  33014. /**
  33015. * Extracts a clone of a mesh geometry
  33016. * @param mesh defines the source mesh
  33017. * @param id defines the unique ID of the new geometry object
  33018. * @returns the new geometry object
  33019. */
  33020. Geometry.ExtractFromMesh = function (mesh, id) {
  33021. var geometry = mesh._geometry;
  33022. if (!geometry) {
  33023. return null;
  33024. }
  33025. return geometry.copy(id);
  33026. };
  33027. /**
  33028. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33029. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33030. * Be aware Math.random() could cause collisions, but:
  33031. * "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"
  33032. * @returns a string containing a new GUID
  33033. */
  33034. Geometry.RandomId = function () {
  33035. return BABYLON.Tools.RandomId();
  33036. };
  33037. /** @ignore */
  33038. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33039. var scene = mesh.getScene();
  33040. // Geometry
  33041. var geometryId = parsedGeometry.geometryId;
  33042. if (geometryId) {
  33043. var geometry = scene.getGeometryByID(geometryId);
  33044. if (geometry) {
  33045. geometry.applyToMesh(mesh);
  33046. }
  33047. }
  33048. else if (parsedGeometry instanceof ArrayBuffer) {
  33049. var binaryInfo = mesh._binaryInfo;
  33050. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33051. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33052. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33053. }
  33054. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33055. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33056. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33057. }
  33058. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33059. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33060. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33061. }
  33062. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33063. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33064. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33065. }
  33066. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33067. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33068. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33069. }
  33070. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33071. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33072. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33073. }
  33074. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33075. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33076. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33077. }
  33078. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33079. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33080. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33081. }
  33082. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33083. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33084. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33085. }
  33086. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33087. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33088. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33089. }
  33090. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33091. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33092. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33093. }
  33094. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33095. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33096. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33097. }
  33098. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33099. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33100. mesh.setIndices(indicesData, null);
  33101. }
  33102. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33103. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33104. mesh.subMeshes = [];
  33105. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33106. var materialIndex = subMeshesData[(i * 5) + 0];
  33107. var verticesStart = subMeshesData[(i * 5) + 1];
  33108. var verticesCount = subMeshesData[(i * 5) + 2];
  33109. var indexStart = subMeshesData[(i * 5) + 3];
  33110. var indexCount = subMeshesData[(i * 5) + 4];
  33111. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33112. }
  33113. }
  33114. }
  33115. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33116. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33117. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33118. if (parsedGeometry.tangents) {
  33119. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33120. }
  33121. if (parsedGeometry.uvs) {
  33122. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33123. }
  33124. if (parsedGeometry.uvs2) {
  33125. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33126. }
  33127. if (parsedGeometry.uvs3) {
  33128. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33129. }
  33130. if (parsedGeometry.uvs4) {
  33131. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33132. }
  33133. if (parsedGeometry.uvs5) {
  33134. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33135. }
  33136. if (parsedGeometry.uvs6) {
  33137. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33138. }
  33139. if (parsedGeometry.colors) {
  33140. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33141. }
  33142. if (parsedGeometry.matricesIndices) {
  33143. if (!parsedGeometry.matricesIndices._isExpanded) {
  33144. var floatIndices = [];
  33145. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33146. var matricesIndex = parsedGeometry.matricesIndices[i];
  33147. floatIndices.push(matricesIndex & 0x000000FF);
  33148. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33149. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33150. floatIndices.push(matricesIndex >> 24);
  33151. }
  33152. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33153. }
  33154. else {
  33155. delete parsedGeometry.matricesIndices._isExpanded;
  33156. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33157. }
  33158. }
  33159. if (parsedGeometry.matricesIndicesExtra) {
  33160. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33161. var floatIndices = [];
  33162. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33163. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33164. floatIndices.push(matricesIndex & 0x000000FF);
  33165. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33166. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33167. floatIndices.push(matricesIndex >> 24);
  33168. }
  33169. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33170. }
  33171. else {
  33172. delete parsedGeometry.matricesIndices._isExpanded;
  33173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33174. }
  33175. }
  33176. if (parsedGeometry.matricesWeights) {
  33177. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33178. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33179. }
  33180. if (parsedGeometry.matricesWeightsExtra) {
  33181. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33182. }
  33183. mesh.setIndices(parsedGeometry.indices, null);
  33184. }
  33185. // SubMeshes
  33186. if (parsedGeometry.subMeshes) {
  33187. mesh.subMeshes = [];
  33188. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33189. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33190. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33191. }
  33192. }
  33193. // Flat shading
  33194. if (mesh._shouldGenerateFlatShading) {
  33195. mesh.convertToFlatShadedMesh();
  33196. delete mesh._shouldGenerateFlatShading;
  33197. }
  33198. // Update
  33199. mesh.computeWorldMatrix(true);
  33200. // Octree
  33201. var sceneOctree = scene.selectionOctree;
  33202. if (sceneOctree !== undefined && sceneOctree !== null) {
  33203. sceneOctree.addMesh(mesh);
  33204. }
  33205. };
  33206. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33207. var epsilon = 1e-3;
  33208. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33209. return;
  33210. }
  33211. var noInfluenceBoneIndex = 0.0;
  33212. if (parsedGeometry.skeletonId > -1) {
  33213. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33214. if (!skeleton) {
  33215. return;
  33216. }
  33217. noInfluenceBoneIndex = skeleton.bones.length;
  33218. }
  33219. else {
  33220. return;
  33221. }
  33222. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33223. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33224. var matricesWeights = parsedGeometry.matricesWeights;
  33225. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33226. var influencers = parsedGeometry.numBoneInfluencer;
  33227. var size = matricesWeights.length;
  33228. for (var i = 0; i < size; i += 4) {
  33229. var weight = 0.0;
  33230. var firstZeroWeight = -1;
  33231. for (var j = 0; j < 4; j++) {
  33232. var w = matricesWeights[i + j];
  33233. weight += w;
  33234. if (w < epsilon && firstZeroWeight < 0) {
  33235. firstZeroWeight = j;
  33236. }
  33237. }
  33238. if (matricesWeightsExtra) {
  33239. for (var j = 0; j < 4; j++) {
  33240. var w = matricesWeightsExtra[i + j];
  33241. weight += w;
  33242. if (w < epsilon && firstZeroWeight < 0) {
  33243. firstZeroWeight = j + 4;
  33244. }
  33245. }
  33246. }
  33247. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33248. firstZeroWeight = influencers - 1;
  33249. }
  33250. if (weight > epsilon) {
  33251. var mweight = 1.0 / weight;
  33252. for (var j = 0; j < 4; j++) {
  33253. matricesWeights[i + j] *= mweight;
  33254. }
  33255. if (matricesWeightsExtra) {
  33256. for (var j = 0; j < 4; j++) {
  33257. matricesWeightsExtra[i + j] *= mweight;
  33258. }
  33259. }
  33260. }
  33261. else {
  33262. if (firstZeroWeight >= 4) {
  33263. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33264. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33265. }
  33266. else {
  33267. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33268. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33269. }
  33270. }
  33271. }
  33272. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33273. if (parsedGeometry.matricesWeightsExtra) {
  33274. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33275. }
  33276. };
  33277. /**
  33278. * Create a new geometry from persisted data (Using .babylon file format)
  33279. * @param parsedVertexData defines the persisted data
  33280. * @param scene defines the hosting scene
  33281. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33282. * @returns the new geometry object
  33283. */
  33284. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33285. if (scene.getGeometryByID(parsedVertexData.id)) {
  33286. return null; // null since geometry could be something else than a box...
  33287. }
  33288. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33289. if (BABYLON.Tags) {
  33290. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33291. }
  33292. if (parsedVertexData.delayLoadingFile) {
  33293. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33294. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33295. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33296. geometry._delayInfo = [];
  33297. if (parsedVertexData.hasUVs) {
  33298. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33299. }
  33300. if (parsedVertexData.hasUVs2) {
  33301. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33302. }
  33303. if (parsedVertexData.hasUVs3) {
  33304. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33305. }
  33306. if (parsedVertexData.hasUVs4) {
  33307. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33308. }
  33309. if (parsedVertexData.hasUVs5) {
  33310. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33311. }
  33312. if (parsedVertexData.hasUVs6) {
  33313. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33314. }
  33315. if (parsedVertexData.hasColors) {
  33316. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33317. }
  33318. if (parsedVertexData.hasMatricesIndices) {
  33319. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33320. }
  33321. if (parsedVertexData.hasMatricesWeights) {
  33322. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33323. }
  33324. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33325. }
  33326. else {
  33327. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33328. }
  33329. scene.pushGeometry(geometry, true);
  33330. return geometry;
  33331. };
  33332. return Geometry;
  33333. }());
  33334. BABYLON.Geometry = Geometry;
  33335. // Primitives
  33336. /// Abstract class
  33337. /**
  33338. * Abstract class used to provide common services for all typed geometries
  33339. */
  33340. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33341. __extends(_PrimitiveGeometry, _super);
  33342. /**
  33343. * Creates a new typed geometry
  33344. * @param id defines the unique ID of the geometry
  33345. * @param scene defines the hosting scene
  33346. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33347. * @param mesh defines the hosting mesh (can be null)
  33348. */
  33349. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33350. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33351. if (mesh === void 0) { mesh = null; }
  33352. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33353. _this._canBeRegenerated = _canBeRegenerated;
  33354. _this._beingRegenerated = true;
  33355. _this.regenerate();
  33356. _this._beingRegenerated = false;
  33357. return _this;
  33358. }
  33359. /**
  33360. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33361. * @returns true if the geometry can be regenerated
  33362. */
  33363. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33364. return this._canBeRegenerated;
  33365. };
  33366. /**
  33367. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33368. */
  33369. _PrimitiveGeometry.prototype.regenerate = function () {
  33370. if (!this._canBeRegenerated) {
  33371. return;
  33372. }
  33373. this._beingRegenerated = true;
  33374. this.setAllVerticesData(this._regenerateVertexData(), false);
  33375. this._beingRegenerated = false;
  33376. };
  33377. /**
  33378. * Clone the geometry
  33379. * @param id defines the unique ID of the new geometry
  33380. * @returns the new geometry
  33381. */
  33382. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33383. return _super.prototype.copy.call(this, id);
  33384. };
  33385. // overrides
  33386. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33387. if (!this._beingRegenerated) {
  33388. return;
  33389. }
  33390. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33391. };
  33392. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33393. if (!this._beingRegenerated) {
  33394. return;
  33395. }
  33396. _super.prototype.setVerticesData.call(this, kind, data, false);
  33397. };
  33398. // to override
  33399. /** @ignore */
  33400. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33401. throw new Error("Abstract method");
  33402. };
  33403. _PrimitiveGeometry.prototype.copy = function (id) {
  33404. throw new Error("Must be overriden in sub-classes.");
  33405. };
  33406. _PrimitiveGeometry.prototype.serialize = function () {
  33407. var serializationObject = _super.prototype.serialize.call(this);
  33408. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33409. return serializationObject;
  33410. };
  33411. return _PrimitiveGeometry;
  33412. }(Geometry));
  33413. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33414. /**
  33415. * Creates a ribbon geometry
  33416. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33417. */
  33418. var RibbonGeometry = /** @class */ (function (_super) {
  33419. __extends(RibbonGeometry, _super);
  33420. /**
  33421. * Creates a ribbon geometry
  33422. * @param id defines the unique ID of the geometry
  33423. * @param scene defines the hosting scene
  33424. * @param pathArray defines the array of paths to use
  33425. * @param closeArray defines if the last path and the first path must be joined
  33426. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33427. * @param offset defines the offset between points
  33428. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33429. * @param mesh defines the hosting mesh (can be null)
  33430. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33431. */
  33432. function RibbonGeometry(id, scene,
  33433. /**
  33434. * Defines the array of paths to use
  33435. */
  33436. pathArray,
  33437. /**
  33438. * Defines if the last and first points of each path in your pathArray must be joined
  33439. */
  33440. closeArray,
  33441. /**
  33442. * Defines if the last and first points of each path in your pathArray must be joined
  33443. */
  33444. closePath,
  33445. /**
  33446. * Defines the offset between points
  33447. */
  33448. offset, canBeRegenerated, mesh,
  33449. /**
  33450. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33451. */
  33452. side) {
  33453. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33454. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33455. _this.pathArray = pathArray;
  33456. _this.closeArray = closeArray;
  33457. _this.closePath = closePath;
  33458. _this.offset = offset;
  33459. _this.side = side;
  33460. return _this;
  33461. }
  33462. /** @ignore */
  33463. RibbonGeometry.prototype._regenerateVertexData = function () {
  33464. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33465. };
  33466. RibbonGeometry.prototype.copy = function (id) {
  33467. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33468. };
  33469. return RibbonGeometry;
  33470. }(_PrimitiveGeometry));
  33471. BABYLON.RibbonGeometry = RibbonGeometry;
  33472. /**
  33473. * Creates a box geometry
  33474. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33475. */
  33476. var BoxGeometry = /** @class */ (function (_super) {
  33477. __extends(BoxGeometry, _super);
  33478. /**
  33479. * Creates a box geometry
  33480. * @param id defines the unique ID of the geometry
  33481. * @param scene defines the hosting scene
  33482. * @param size defines the zise of the box (width, height and depth are the same)
  33483. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33484. * @param mesh defines the hosting mesh (can be null)
  33485. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33486. */
  33487. function BoxGeometry(id, scene,
  33488. /**
  33489. * Defines the zise of the box (width, height and depth are the same)
  33490. */
  33491. size, canBeRegenerated, mesh,
  33492. /**
  33493. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33494. */
  33495. side) {
  33496. if (mesh === void 0) { mesh = null; }
  33497. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33498. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33499. _this.size = size;
  33500. _this.side = side;
  33501. return _this;
  33502. }
  33503. BoxGeometry.prototype._regenerateVertexData = function () {
  33504. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33505. };
  33506. BoxGeometry.prototype.copy = function (id) {
  33507. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33508. };
  33509. BoxGeometry.prototype.serialize = function () {
  33510. var serializationObject = _super.prototype.serialize.call(this);
  33511. serializationObject.size = this.size;
  33512. return serializationObject;
  33513. };
  33514. BoxGeometry.Parse = function (parsedBox, scene) {
  33515. if (scene.getGeometryByID(parsedBox.id)) {
  33516. return null; // null since geometry could be something else than a box...
  33517. }
  33518. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33519. if (BABYLON.Tags) {
  33520. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33521. }
  33522. scene.pushGeometry(box, true);
  33523. return box;
  33524. };
  33525. return BoxGeometry;
  33526. }(_PrimitiveGeometry));
  33527. BABYLON.BoxGeometry = BoxGeometry;
  33528. /**
  33529. * Creates a sphere geometry
  33530. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33531. */
  33532. var SphereGeometry = /** @class */ (function (_super) {
  33533. __extends(SphereGeometry, _super);
  33534. /**
  33535. * Create a new sphere geometry
  33536. * @param id defines the unique ID of the geometry
  33537. * @param scene defines the hosting scene
  33538. * @param segments defines the number of segments to use to create the sphere
  33539. * @param diameter defines the diameter of the sphere
  33540. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33541. * @param mesh defines the hosting mesh (can be null)
  33542. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33543. */
  33544. function SphereGeometry(id, scene,
  33545. /**
  33546. * Defines the number of segments to use to create the sphere
  33547. */
  33548. segments,
  33549. /**
  33550. * Defines the diameter of the sphere
  33551. */
  33552. diameter, canBeRegenerated, mesh,
  33553. /**
  33554. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33555. */
  33556. side) {
  33557. if (mesh === void 0) { mesh = null; }
  33558. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33559. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33560. _this.segments = segments;
  33561. _this.diameter = diameter;
  33562. _this.side = side;
  33563. return _this;
  33564. }
  33565. SphereGeometry.prototype._regenerateVertexData = function () {
  33566. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33567. };
  33568. SphereGeometry.prototype.copy = function (id) {
  33569. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33570. };
  33571. SphereGeometry.prototype.serialize = function () {
  33572. var serializationObject = _super.prototype.serialize.call(this);
  33573. serializationObject.segments = this.segments;
  33574. serializationObject.diameter = this.diameter;
  33575. return serializationObject;
  33576. };
  33577. SphereGeometry.Parse = function (parsedSphere, scene) {
  33578. if (scene.getGeometryByID(parsedSphere.id)) {
  33579. return null; // null since geometry could be something else than a sphere...
  33580. }
  33581. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33582. if (BABYLON.Tags) {
  33583. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33584. }
  33585. scene.pushGeometry(sphere, true);
  33586. return sphere;
  33587. };
  33588. return SphereGeometry;
  33589. }(_PrimitiveGeometry));
  33590. BABYLON.SphereGeometry = SphereGeometry;
  33591. /**
  33592. * Creates a disc geometry
  33593. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33594. */
  33595. var DiscGeometry = /** @class */ (function (_super) {
  33596. __extends(DiscGeometry, _super);
  33597. /**
  33598. * Creates a new disc geometry
  33599. * @param id defines the unique ID of the geometry
  33600. * @param scene defines the hosting scene
  33601. * @param radius defines the radius of the disc
  33602. * @param tessellation defines the tesselation factor to apply to the disc
  33603. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33604. * @param mesh defines the hosting mesh (can be null)
  33605. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33606. */
  33607. function DiscGeometry(id, scene,
  33608. /**
  33609. * Defines the radius of the disc
  33610. */
  33611. radius,
  33612. /**
  33613. * Defines the tesselation factor to apply to the disc
  33614. */
  33615. tessellation, canBeRegenerated, mesh,
  33616. /**
  33617. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33618. */
  33619. side) {
  33620. if (mesh === void 0) { mesh = null; }
  33621. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33622. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33623. _this.radius = radius;
  33624. _this.tessellation = tessellation;
  33625. _this.side = side;
  33626. return _this;
  33627. }
  33628. DiscGeometry.prototype._regenerateVertexData = function () {
  33629. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33630. };
  33631. DiscGeometry.prototype.copy = function (id) {
  33632. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33633. };
  33634. return DiscGeometry;
  33635. }(_PrimitiveGeometry));
  33636. BABYLON.DiscGeometry = DiscGeometry;
  33637. /**
  33638. * Creates a new cylinder geometry
  33639. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33640. */
  33641. var CylinderGeometry = /** @class */ (function (_super) {
  33642. __extends(CylinderGeometry, _super);
  33643. /**
  33644. * Creates a new cylinder geometry
  33645. * @param id defines the unique ID of the geometry
  33646. * @param scene defines the hosting scene
  33647. * @param height defines the height of the cylinder
  33648. * @param diameterTop defines the diameter of the cylinder's top cap
  33649. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33650. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33651. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33652. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33653. * @param mesh defines the hosting mesh (can be null)
  33654. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33655. */
  33656. function CylinderGeometry(id, scene,
  33657. /**
  33658. * Defines the height of the cylinder
  33659. */
  33660. height,
  33661. /**
  33662. * Defines the diameter of the cylinder's top cap
  33663. */
  33664. diameterTop,
  33665. /**
  33666. * Defines the diameter of the cylinder's bottom cap
  33667. */
  33668. diameterBottom,
  33669. /**
  33670. * Defines the tessellation factor to apply to the cylinder
  33671. */
  33672. tessellation,
  33673. /**
  33674. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33675. */
  33676. subdivisions, canBeRegenerated, mesh,
  33677. /**
  33678. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33679. */
  33680. side) {
  33681. if (subdivisions === void 0) { subdivisions = 1; }
  33682. if (mesh === void 0) { mesh = null; }
  33683. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33684. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33685. _this.height = height;
  33686. _this.diameterTop = diameterTop;
  33687. _this.diameterBottom = diameterBottom;
  33688. _this.tessellation = tessellation;
  33689. _this.subdivisions = subdivisions;
  33690. _this.side = side;
  33691. return _this;
  33692. }
  33693. CylinderGeometry.prototype._regenerateVertexData = function () {
  33694. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33695. };
  33696. CylinderGeometry.prototype.copy = function (id) {
  33697. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33698. };
  33699. CylinderGeometry.prototype.serialize = function () {
  33700. var serializationObject = _super.prototype.serialize.call(this);
  33701. serializationObject.height = this.height;
  33702. serializationObject.diameterTop = this.diameterTop;
  33703. serializationObject.diameterBottom = this.diameterBottom;
  33704. serializationObject.tessellation = this.tessellation;
  33705. return serializationObject;
  33706. };
  33707. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  33708. if (scene.getGeometryByID(parsedCylinder.id)) {
  33709. return null; // null since geometry could be something else than a cylinder...
  33710. }
  33711. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33712. if (BABYLON.Tags) {
  33713. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33714. }
  33715. scene.pushGeometry(cylinder, true);
  33716. return cylinder;
  33717. };
  33718. return CylinderGeometry;
  33719. }(_PrimitiveGeometry));
  33720. BABYLON.CylinderGeometry = CylinderGeometry;
  33721. /**
  33722. * Creates a new torus geometry
  33723. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  33724. */
  33725. var TorusGeometry = /** @class */ (function (_super) {
  33726. __extends(TorusGeometry, _super);
  33727. /**
  33728. * Creates a new torus geometry
  33729. * @param id defines the unique ID of the geometry
  33730. * @param scene defines the hosting scene
  33731. * @param diameter defines the diameter of the torus
  33732. * @param thickness defines the thickness of the torus (ie. internal diameter)
  33733. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  33734. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33735. * @param mesh defines the hosting mesh (can be null)
  33736. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33737. */
  33738. function TorusGeometry(id, scene,
  33739. /**
  33740. * Defines the diameter of the torus
  33741. */
  33742. diameter,
  33743. /**
  33744. * Defines the thickness of the torus (ie. internal diameter)
  33745. */
  33746. thickness,
  33747. /**
  33748. * Defines the tesselation factor to apply to the torus
  33749. */
  33750. tessellation, canBeRegenerated, mesh,
  33751. /**
  33752. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33753. */
  33754. side) {
  33755. if (mesh === void 0) { mesh = null; }
  33756. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33757. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33758. _this.diameter = diameter;
  33759. _this.thickness = thickness;
  33760. _this.tessellation = tessellation;
  33761. _this.side = side;
  33762. return _this;
  33763. }
  33764. TorusGeometry.prototype._regenerateVertexData = function () {
  33765. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33766. };
  33767. TorusGeometry.prototype.copy = function (id) {
  33768. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33769. };
  33770. TorusGeometry.prototype.serialize = function () {
  33771. var serializationObject = _super.prototype.serialize.call(this);
  33772. serializationObject.diameter = this.diameter;
  33773. serializationObject.thickness = this.thickness;
  33774. serializationObject.tessellation = this.tessellation;
  33775. return serializationObject;
  33776. };
  33777. TorusGeometry.Parse = function (parsedTorus, scene) {
  33778. if (scene.getGeometryByID(parsedTorus.id)) {
  33779. return null; // null since geometry could be something else than a torus...
  33780. }
  33781. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33782. if (BABYLON.Tags) {
  33783. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33784. }
  33785. scene.pushGeometry(torus, true);
  33786. return torus;
  33787. };
  33788. return TorusGeometry;
  33789. }(_PrimitiveGeometry));
  33790. BABYLON.TorusGeometry = TorusGeometry;
  33791. /**
  33792. * Creates a new ground geometry
  33793. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  33794. */
  33795. var GroundGeometry = /** @class */ (function (_super) {
  33796. __extends(GroundGeometry, _super);
  33797. /**
  33798. * Creates a new ground geometry
  33799. * @param id defines the unique ID of the geometry
  33800. * @param scene defines the hosting scene
  33801. * @param width defines the width of the ground
  33802. * @param height defines the height of the ground
  33803. * @param subdivisions defines the subdivisions to apply to the ground
  33804. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33805. * @param mesh defines the hosting mesh (can be null)
  33806. */
  33807. function GroundGeometry(id, scene,
  33808. /**
  33809. * Defines the width of the ground
  33810. */
  33811. width,
  33812. /**
  33813. * Defines the height of the ground
  33814. */
  33815. height,
  33816. /**
  33817. * Defines the subdivisions to apply to the ground
  33818. */
  33819. subdivisions, canBeRegenerated, mesh) {
  33820. if (mesh === void 0) { mesh = null; }
  33821. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33822. _this.width = width;
  33823. _this.height = height;
  33824. _this.subdivisions = subdivisions;
  33825. return _this;
  33826. }
  33827. GroundGeometry.prototype._regenerateVertexData = function () {
  33828. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33829. };
  33830. GroundGeometry.prototype.copy = function (id) {
  33831. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33832. };
  33833. GroundGeometry.prototype.serialize = function () {
  33834. var serializationObject = _super.prototype.serialize.call(this);
  33835. serializationObject.width = this.width;
  33836. serializationObject.height = this.height;
  33837. serializationObject.subdivisions = this.subdivisions;
  33838. return serializationObject;
  33839. };
  33840. GroundGeometry.Parse = function (parsedGround, scene) {
  33841. if (scene.getGeometryByID(parsedGround.id)) {
  33842. return null; // null since geometry could be something else than a ground...
  33843. }
  33844. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33845. if (BABYLON.Tags) {
  33846. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33847. }
  33848. scene.pushGeometry(ground, true);
  33849. return ground;
  33850. };
  33851. return GroundGeometry;
  33852. }(_PrimitiveGeometry));
  33853. BABYLON.GroundGeometry = GroundGeometry;
  33854. /**
  33855. * Creates a tiled ground geometry
  33856. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  33857. */
  33858. var TiledGroundGeometry = /** @class */ (function (_super) {
  33859. __extends(TiledGroundGeometry, _super);
  33860. /**
  33861. * Creates a tiled ground geometry
  33862. * @param id defines the unique ID of the geometry
  33863. * @param scene defines the hosting scene
  33864. * @param xmin defines the minimum value on X axis
  33865. * @param zmin defines the minimum value on Z axis
  33866. * @param xmax defines the maximum value on X axis
  33867. * @param zmax defines the maximum value on Z axis
  33868. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  33869. * @param precision defines the precision to use when computing the tiles
  33870. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33871. * @param mesh defines the hosting mesh (can be null)
  33872. */
  33873. function TiledGroundGeometry(id, scene,
  33874. /**
  33875. * Defines the minimum value on X axis
  33876. */
  33877. xmin,
  33878. /**
  33879. * Defines the minimum value on Z axis
  33880. */
  33881. zmin,
  33882. /**
  33883. * Defines the maximum value on X axis
  33884. */
  33885. xmax,
  33886. /**
  33887. * Defines the maximum value on Z axis
  33888. */
  33889. zmax,
  33890. /**
  33891. * Defines the subdivisions to apply to the ground
  33892. */
  33893. subdivisions,
  33894. /**
  33895. * Defines the precision to use when computing the tiles
  33896. */
  33897. precision, canBeRegenerated, mesh) {
  33898. if (mesh === void 0) { mesh = null; }
  33899. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33900. _this.xmin = xmin;
  33901. _this.zmin = zmin;
  33902. _this.xmax = xmax;
  33903. _this.zmax = zmax;
  33904. _this.subdivisions = subdivisions;
  33905. _this.precision = precision;
  33906. return _this;
  33907. }
  33908. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  33909. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33910. };
  33911. TiledGroundGeometry.prototype.copy = function (id) {
  33912. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33913. };
  33914. return TiledGroundGeometry;
  33915. }(_PrimitiveGeometry));
  33916. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  33917. /**
  33918. * Creates a plane geometry
  33919. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  33920. */
  33921. var PlaneGeometry = /** @class */ (function (_super) {
  33922. __extends(PlaneGeometry, _super);
  33923. /**
  33924. * Creates a plane geometry
  33925. * @param id defines the unique ID of the geometry
  33926. * @param scene defines the hosting scene
  33927. * @param size defines the size of the plane (width === height)
  33928. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33929. * @param mesh defines the hosting mesh (can be null)
  33930. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33931. */
  33932. function PlaneGeometry(id, scene,
  33933. /**
  33934. * Defines the size of the plane (width === height)
  33935. */
  33936. size, canBeRegenerated, mesh,
  33937. /**
  33938. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33939. */
  33940. side) {
  33941. if (mesh === void 0) { mesh = null; }
  33942. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33943. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33944. _this.size = size;
  33945. _this.side = side;
  33946. return _this;
  33947. }
  33948. PlaneGeometry.prototype._regenerateVertexData = function () {
  33949. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  33950. };
  33951. PlaneGeometry.prototype.copy = function (id) {
  33952. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  33953. };
  33954. PlaneGeometry.prototype.serialize = function () {
  33955. var serializationObject = _super.prototype.serialize.call(this);
  33956. serializationObject.size = this.size;
  33957. return serializationObject;
  33958. };
  33959. PlaneGeometry.Parse = function (parsedPlane, scene) {
  33960. if (scene.getGeometryByID(parsedPlane.id)) {
  33961. return null; // null since geometry could be something else than a ground...
  33962. }
  33963. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  33964. if (BABYLON.Tags) {
  33965. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  33966. }
  33967. scene.pushGeometry(plane, true);
  33968. return plane;
  33969. };
  33970. return PlaneGeometry;
  33971. }(_PrimitiveGeometry));
  33972. BABYLON.PlaneGeometry = PlaneGeometry;
  33973. /**
  33974. * Creates a torus knot geometry
  33975. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  33976. */
  33977. var TorusKnotGeometry = /** @class */ (function (_super) {
  33978. __extends(TorusKnotGeometry, _super);
  33979. /**
  33980. * Creates a torus knot geometry
  33981. * @param id defines the unique ID of the geometry
  33982. * @param scene defines the hosting scene
  33983. * @param radius defines the radius of the torus knot
  33984. * @param tube defines the thickness of the torus knot tube
  33985. * @param radialSegments defines the number of radial segments
  33986. * @param tubularSegments defines the number of tubular segments
  33987. * @param p defines the first number of windings
  33988. * @param q defines the second number of windings
  33989. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33990. * @param mesh defines the hosting mesh (can be null)
  33991. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33992. */
  33993. function TorusKnotGeometry(id, scene,
  33994. /**
  33995. * Defines the radius of the torus knot
  33996. */
  33997. radius,
  33998. /**
  33999. * Defines the thickness of the torus knot tube
  34000. */
  34001. tube,
  34002. /**
  34003. * Defines the number of radial segments
  34004. */
  34005. radialSegments,
  34006. /**
  34007. * Defines the number of tubular segments
  34008. */
  34009. tubularSegments,
  34010. /**
  34011. * Defines the first number of windings
  34012. */
  34013. p,
  34014. /**
  34015. * Defines the second number of windings
  34016. */
  34017. q, canBeRegenerated, mesh,
  34018. /**
  34019. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34020. */
  34021. side) {
  34022. if (mesh === void 0) { mesh = null; }
  34023. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34024. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34025. _this.radius = radius;
  34026. _this.tube = tube;
  34027. _this.radialSegments = radialSegments;
  34028. _this.tubularSegments = tubularSegments;
  34029. _this.p = p;
  34030. _this.q = q;
  34031. _this.side = side;
  34032. return _this;
  34033. }
  34034. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34035. 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 });
  34036. };
  34037. TorusKnotGeometry.prototype.copy = function (id) {
  34038. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34039. };
  34040. TorusKnotGeometry.prototype.serialize = function () {
  34041. var serializationObject = _super.prototype.serialize.call(this);
  34042. serializationObject.radius = this.radius;
  34043. serializationObject.tube = this.tube;
  34044. serializationObject.radialSegments = this.radialSegments;
  34045. serializationObject.tubularSegments = this.tubularSegments;
  34046. serializationObject.p = this.p;
  34047. serializationObject.q = this.q;
  34048. return serializationObject;
  34049. };
  34050. ;
  34051. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34052. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34053. return null; // null since geometry could be something else than a ground...
  34054. }
  34055. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34056. if (BABYLON.Tags) {
  34057. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34058. }
  34059. scene.pushGeometry(torusKnot, true);
  34060. return torusKnot;
  34061. };
  34062. return TorusKnotGeometry;
  34063. }(_PrimitiveGeometry));
  34064. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34065. //}
  34066. })(BABYLON || (BABYLON = {}));
  34067. //# sourceMappingURL=babylon.geometry.js.map
  34068. var BABYLON;
  34069. (function (BABYLON) {
  34070. var PostProcessManager = /** @class */ (function () {
  34071. function PostProcessManager(scene) {
  34072. this._vertexBuffers = {};
  34073. this._scene = scene;
  34074. }
  34075. PostProcessManager.prototype._prepareBuffers = function () {
  34076. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34077. return;
  34078. }
  34079. // VBO
  34080. var vertices = [];
  34081. vertices.push(1, 1);
  34082. vertices.push(-1, 1);
  34083. vertices.push(-1, -1);
  34084. vertices.push(1, -1);
  34085. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34086. this._buildIndexBuffer();
  34087. };
  34088. PostProcessManager.prototype._buildIndexBuffer = function () {
  34089. // Indices
  34090. var indices = [];
  34091. indices.push(0);
  34092. indices.push(1);
  34093. indices.push(2);
  34094. indices.push(0);
  34095. indices.push(2);
  34096. indices.push(3);
  34097. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34098. };
  34099. PostProcessManager.prototype._rebuild = function () {
  34100. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34101. if (!vb) {
  34102. return;
  34103. }
  34104. vb._rebuild();
  34105. this._buildIndexBuffer();
  34106. };
  34107. // Methods
  34108. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34109. if (sourceTexture === void 0) { sourceTexture = null; }
  34110. if (postProcesses === void 0) { postProcesses = null; }
  34111. var camera = this._scene.activeCamera;
  34112. if (!camera) {
  34113. return false;
  34114. }
  34115. var postProcesses = postProcesses || camera._postProcesses;
  34116. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34117. return false;
  34118. }
  34119. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34120. return true;
  34121. };
  34122. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34123. if (targetTexture === void 0) { targetTexture = null; }
  34124. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34125. var engine = this._scene.getEngine();
  34126. for (var index = 0; index < postProcesses.length; index++) {
  34127. if (index < postProcesses.length - 1) {
  34128. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34129. }
  34130. else {
  34131. if (targetTexture) {
  34132. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34133. }
  34134. else {
  34135. engine.restoreDefaultFramebuffer();
  34136. }
  34137. }
  34138. var pp = postProcesses[index];
  34139. var effect = pp.apply();
  34140. if (effect) {
  34141. pp.onBeforeRenderObservable.notifyObservers(effect);
  34142. // VBOs
  34143. this._prepareBuffers();
  34144. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34145. // Draw order
  34146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34147. pp.onAfterRenderObservable.notifyObservers(effect);
  34148. }
  34149. }
  34150. // Restore depth buffer
  34151. engine.setDepthBuffer(true);
  34152. engine.setDepthWrite(true);
  34153. };
  34154. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34155. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34156. var camera = this._scene.activeCamera;
  34157. if (!camera) {
  34158. return;
  34159. }
  34160. postProcesses = postProcesses || camera._postProcesses;
  34161. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34162. return;
  34163. }
  34164. var engine = this._scene.getEngine();
  34165. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34166. if (index < len - 1) {
  34167. postProcesses[index + 1].activate(camera, targetTexture);
  34168. }
  34169. else {
  34170. if (targetTexture) {
  34171. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34172. }
  34173. else {
  34174. engine.restoreDefaultFramebuffer();
  34175. }
  34176. }
  34177. if (doNotPresent) {
  34178. break;
  34179. }
  34180. var pp = postProcesses[index];
  34181. var effect = pp.apply();
  34182. if (effect) {
  34183. pp.onBeforeRenderObservable.notifyObservers(effect);
  34184. // VBOs
  34185. this._prepareBuffers();
  34186. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34187. // Draw order
  34188. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34189. pp.onAfterRenderObservable.notifyObservers(effect);
  34190. }
  34191. }
  34192. // Restore states
  34193. engine.setDepthBuffer(true);
  34194. engine.setDepthWrite(true);
  34195. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34196. };
  34197. PostProcessManager.prototype.dispose = function () {
  34198. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34199. if (buffer) {
  34200. buffer.dispose();
  34201. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34202. }
  34203. if (this._indexBuffer) {
  34204. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34205. this._indexBuffer = null;
  34206. }
  34207. };
  34208. return PostProcessManager;
  34209. }());
  34210. BABYLON.PostProcessManager = PostProcessManager;
  34211. })(BABYLON || (BABYLON = {}));
  34212. //# sourceMappingURL=babylon.postProcessManager.js.map
  34213. var BABYLON;
  34214. (function (BABYLON) {
  34215. /**
  34216. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34217. */
  34218. var PerformanceMonitor = /** @class */ (function () {
  34219. /**
  34220. * constructor
  34221. * @param frameSampleSize The number of samples required to saturate the sliding window
  34222. */
  34223. function PerformanceMonitor(frameSampleSize) {
  34224. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34225. this._enabled = true;
  34226. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34227. }
  34228. /**
  34229. * Samples current frame
  34230. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34231. */
  34232. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34233. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34234. if (!this._enabled)
  34235. return;
  34236. if (this._lastFrameTimeMs != null) {
  34237. var dt = timeMs - this._lastFrameTimeMs;
  34238. this._rollingFrameTime.add(dt);
  34239. }
  34240. this._lastFrameTimeMs = timeMs;
  34241. };
  34242. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34243. /**
  34244. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34245. * @return Average frame time in milliseconds
  34246. */
  34247. get: function () {
  34248. return this._rollingFrameTime.average;
  34249. },
  34250. enumerable: true,
  34251. configurable: true
  34252. });
  34253. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34254. /**
  34255. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34256. * @return Frame time variance in milliseconds squared
  34257. */
  34258. get: function () {
  34259. return this._rollingFrameTime.variance;
  34260. },
  34261. enumerable: true,
  34262. configurable: true
  34263. });
  34264. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34265. /**
  34266. * Returns the frame time of the most recent frame
  34267. * @return Frame time in milliseconds
  34268. */
  34269. get: function () {
  34270. return this._rollingFrameTime.history(0);
  34271. },
  34272. enumerable: true,
  34273. configurable: true
  34274. });
  34275. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34276. /**
  34277. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34278. * @return Framerate in frames per second
  34279. */
  34280. get: function () {
  34281. return 1000.0 / this._rollingFrameTime.average;
  34282. },
  34283. enumerable: true,
  34284. configurable: true
  34285. });
  34286. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34287. /**
  34288. * Returns the average framerate in frames per second using the most recent frame time
  34289. * @return Framerate in frames per second
  34290. */
  34291. get: function () {
  34292. var history = this._rollingFrameTime.history(0);
  34293. if (history === 0) {
  34294. return 0;
  34295. }
  34296. return 1000.0 / history;
  34297. },
  34298. enumerable: true,
  34299. configurable: true
  34300. });
  34301. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34302. /**
  34303. * Returns true if enough samples have been taken to completely fill the sliding window
  34304. * @return true if saturated
  34305. */
  34306. get: function () {
  34307. return this._rollingFrameTime.isSaturated();
  34308. },
  34309. enumerable: true,
  34310. configurable: true
  34311. });
  34312. /**
  34313. * Enables contributions to the sliding window sample set
  34314. */
  34315. PerformanceMonitor.prototype.enable = function () {
  34316. this._enabled = true;
  34317. };
  34318. /**
  34319. * Disables contributions to the sliding window sample set
  34320. * Samples will not be interpolated over the disabled period
  34321. */
  34322. PerformanceMonitor.prototype.disable = function () {
  34323. this._enabled = false;
  34324. //clear last sample to avoid interpolating over the disabled period when next enabled
  34325. this._lastFrameTimeMs = null;
  34326. };
  34327. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34328. /**
  34329. * Returns true if sampling is enabled
  34330. * @return true if enabled
  34331. */
  34332. get: function () {
  34333. return this._enabled;
  34334. },
  34335. enumerable: true,
  34336. configurable: true
  34337. });
  34338. /**
  34339. * Resets performance monitor
  34340. */
  34341. PerformanceMonitor.prototype.reset = function () {
  34342. //clear last sample to avoid interpolating over the disabled period when next enabled
  34343. this._lastFrameTimeMs = null;
  34344. //wipe record
  34345. this._rollingFrameTime.reset();
  34346. };
  34347. return PerformanceMonitor;
  34348. }());
  34349. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34350. /**
  34351. * RollingAverage
  34352. *
  34353. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34354. */
  34355. var RollingAverage = /** @class */ (function () {
  34356. /**
  34357. * constructor
  34358. * @param length The number of samples required to saturate the sliding window
  34359. */
  34360. function RollingAverage(length) {
  34361. this._samples = new Array(length);
  34362. this.reset();
  34363. }
  34364. /**
  34365. * Adds a sample to the sample set
  34366. * @param v The sample value
  34367. */
  34368. RollingAverage.prototype.add = function (v) {
  34369. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34370. var delta;
  34371. //we need to check if we've already wrapped round
  34372. if (this.isSaturated()) {
  34373. //remove bottom of stack from mean
  34374. var bottomValue = this._samples[this._pos];
  34375. delta = bottomValue - this.average;
  34376. this.average -= delta / (this._sampleCount - 1);
  34377. this._m2 -= delta * (bottomValue - this.average);
  34378. }
  34379. else {
  34380. this._sampleCount++;
  34381. }
  34382. //add new value to mean
  34383. delta = v - this.average;
  34384. this.average += delta / (this._sampleCount);
  34385. this._m2 += delta * (v - this.average);
  34386. //set the new variance
  34387. this.variance = this._m2 / (this._sampleCount - 1);
  34388. this._samples[this._pos] = v;
  34389. this._pos++;
  34390. this._pos %= this._samples.length; //positive wrap around
  34391. };
  34392. /**
  34393. * Returns previously added values or null if outside of history or outside the sliding window domain
  34394. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34395. * @return Value previously recorded with add() or null if outside of range
  34396. */
  34397. RollingAverage.prototype.history = function (i) {
  34398. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34399. return 0;
  34400. }
  34401. var i0 = this._wrapPosition(this._pos - 1.0);
  34402. return this._samples[this._wrapPosition(i0 - i)];
  34403. };
  34404. /**
  34405. * Returns true if enough samples have been taken to completely fill the sliding window
  34406. * @return true if sample-set saturated
  34407. */
  34408. RollingAverage.prototype.isSaturated = function () {
  34409. return this._sampleCount >= this._samples.length;
  34410. };
  34411. /**
  34412. * Resets the rolling average (equivalent to 0 samples taken so far)
  34413. */
  34414. RollingAverage.prototype.reset = function () {
  34415. this.average = 0;
  34416. this.variance = 0;
  34417. this._sampleCount = 0;
  34418. this._pos = 0;
  34419. this._m2 = 0;
  34420. };
  34421. /**
  34422. * Wraps a value around the sample range boundaries
  34423. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34424. * @return Wrapped position in sample range
  34425. */
  34426. RollingAverage.prototype._wrapPosition = function (i) {
  34427. var max = this._samples.length;
  34428. return ((i % max) + max) % max;
  34429. };
  34430. return RollingAverage;
  34431. }());
  34432. BABYLON.RollingAverage = RollingAverage;
  34433. })(BABYLON || (BABYLON = {}));
  34434. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34435. var BABYLON;
  34436. (function (BABYLON) {
  34437. /**
  34438. * This groups together the common properties used for image processing either in direct forward pass
  34439. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34440. * or not.
  34441. */
  34442. var ImageProcessingConfiguration = /** @class */ (function () {
  34443. function ImageProcessingConfiguration() {
  34444. /**
  34445. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34446. */
  34447. this.colorCurves = new BABYLON.ColorCurves();
  34448. this._colorCurvesEnabled = false;
  34449. this._colorGradingEnabled = false;
  34450. this._colorGradingWithGreenDepth = true;
  34451. this._colorGradingBGR = true;
  34452. this._exposure = 1.0;
  34453. this._toneMappingEnabled = false;
  34454. this._contrast = 1.0;
  34455. /**
  34456. * Vignette stretch size.
  34457. */
  34458. this.vignetteStretch = 0;
  34459. /**
  34460. * Vignette centre X Offset.
  34461. */
  34462. this.vignetteCentreX = 0;
  34463. /**
  34464. * Vignette centre Y Offset.
  34465. */
  34466. this.vignetteCentreY = 0;
  34467. /**
  34468. * Vignette weight or intensity of the vignette effect.
  34469. */
  34470. this.vignetteWeight = 1.5;
  34471. /**
  34472. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34473. * if vignetteEnabled is set to true.
  34474. */
  34475. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34476. /**
  34477. * Camera field of view used by the Vignette effect.
  34478. */
  34479. this.vignetteCameraFov = 0.5;
  34480. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34481. this._vignetteEnabled = false;
  34482. this._applyByPostProcess = false;
  34483. this._isEnabled = true;
  34484. /**
  34485. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34486. * @type {BABYLON.Observable}
  34487. */
  34488. this.onUpdateParameters = new BABYLON.Observable();
  34489. }
  34490. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34491. /**
  34492. * Gets wether the color curves effect is enabled.
  34493. */
  34494. get: function () {
  34495. return this._colorCurvesEnabled;
  34496. },
  34497. /**
  34498. * Sets wether the color curves effect is enabled.
  34499. */
  34500. set: function (value) {
  34501. if (this._colorCurvesEnabled === value) {
  34502. return;
  34503. }
  34504. this._colorCurvesEnabled = value;
  34505. this._updateParameters();
  34506. },
  34507. enumerable: true,
  34508. configurable: true
  34509. });
  34510. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34511. /**
  34512. * Gets wether the color grading effect is enabled.
  34513. */
  34514. get: function () {
  34515. return this._colorGradingEnabled;
  34516. },
  34517. /**
  34518. * Sets wether the color grading effect is enabled.
  34519. */
  34520. set: function (value) {
  34521. if (this._colorGradingEnabled === value) {
  34522. return;
  34523. }
  34524. this._colorGradingEnabled = value;
  34525. this._updateParameters();
  34526. },
  34527. enumerable: true,
  34528. configurable: true
  34529. });
  34530. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34531. /**
  34532. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34533. */
  34534. get: function () {
  34535. return this._colorGradingWithGreenDepth;
  34536. },
  34537. /**
  34538. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34539. */
  34540. set: function (value) {
  34541. if (this._colorGradingWithGreenDepth === value) {
  34542. return;
  34543. }
  34544. this._colorGradingWithGreenDepth = value;
  34545. this._updateParameters();
  34546. },
  34547. enumerable: true,
  34548. configurable: true
  34549. });
  34550. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34551. /**
  34552. * Gets wether the color grading texture contains BGR values.
  34553. */
  34554. get: function () {
  34555. return this._colorGradingBGR;
  34556. },
  34557. /**
  34558. * Sets wether the color grading texture contains BGR values.
  34559. */
  34560. set: function (value) {
  34561. if (this._colorGradingBGR === value) {
  34562. return;
  34563. }
  34564. this._colorGradingBGR = value;
  34565. this._updateParameters();
  34566. },
  34567. enumerable: true,
  34568. configurable: true
  34569. });
  34570. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34571. /**
  34572. * Gets the Exposure used in the effect.
  34573. */
  34574. get: function () {
  34575. return this._exposure;
  34576. },
  34577. /**
  34578. * Sets the Exposure used in the effect.
  34579. */
  34580. set: function (value) {
  34581. if (this._exposure === value) {
  34582. return;
  34583. }
  34584. this._exposure = value;
  34585. this._updateParameters();
  34586. },
  34587. enumerable: true,
  34588. configurable: true
  34589. });
  34590. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34591. /**
  34592. * Gets wether the tone mapping effect is enabled.
  34593. */
  34594. get: function () {
  34595. return this._toneMappingEnabled;
  34596. },
  34597. /**
  34598. * Sets wether the tone mapping effect is enabled.
  34599. */
  34600. set: function (value) {
  34601. if (this._toneMappingEnabled === value) {
  34602. return;
  34603. }
  34604. this._toneMappingEnabled = value;
  34605. this._updateParameters();
  34606. },
  34607. enumerable: true,
  34608. configurable: true
  34609. });
  34610. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34611. /**
  34612. * Gets the contrast used in the effect.
  34613. */
  34614. get: function () {
  34615. return this._contrast;
  34616. },
  34617. /**
  34618. * Sets the contrast used in the effect.
  34619. */
  34620. set: function (value) {
  34621. if (this._contrast === value) {
  34622. return;
  34623. }
  34624. this._contrast = value;
  34625. this._updateParameters();
  34626. },
  34627. enumerable: true,
  34628. configurable: true
  34629. });
  34630. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34631. /**
  34632. * Gets the vignette blend mode allowing different kind of effect.
  34633. */
  34634. get: function () {
  34635. return this._vignetteBlendMode;
  34636. },
  34637. /**
  34638. * Sets the vignette blend mode allowing different kind of effect.
  34639. */
  34640. set: function (value) {
  34641. if (this._vignetteBlendMode === value) {
  34642. return;
  34643. }
  34644. this._vignetteBlendMode = value;
  34645. this._updateParameters();
  34646. },
  34647. enumerable: true,
  34648. configurable: true
  34649. });
  34650. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34651. /**
  34652. * Gets wether the vignette effect is enabled.
  34653. */
  34654. get: function () {
  34655. return this._vignetteEnabled;
  34656. },
  34657. /**
  34658. * Sets wether the vignette effect is enabled.
  34659. */
  34660. set: function (value) {
  34661. if (this._vignetteEnabled === value) {
  34662. return;
  34663. }
  34664. this._vignetteEnabled = value;
  34665. this._updateParameters();
  34666. },
  34667. enumerable: true,
  34668. configurable: true
  34669. });
  34670. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34671. /**
  34672. * Gets wether the image processing is applied through a post process or not.
  34673. */
  34674. get: function () {
  34675. return this._applyByPostProcess;
  34676. },
  34677. /**
  34678. * Sets wether the image processing is applied through a post process or not.
  34679. */
  34680. set: function (value) {
  34681. if (this._applyByPostProcess === value) {
  34682. return;
  34683. }
  34684. this._applyByPostProcess = value;
  34685. this._updateParameters();
  34686. },
  34687. enumerable: true,
  34688. configurable: true
  34689. });
  34690. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34691. /**
  34692. * Gets wether the image processing is enabled or not.
  34693. */
  34694. get: function () {
  34695. return this._isEnabled;
  34696. },
  34697. /**
  34698. * Sets wether the image processing is enabled or not.
  34699. */
  34700. set: function (value) {
  34701. if (this._isEnabled === value) {
  34702. return;
  34703. }
  34704. this._isEnabled = value;
  34705. this._updateParameters();
  34706. },
  34707. enumerable: true,
  34708. configurable: true
  34709. });
  34710. /**
  34711. * Method called each time the image processing information changes requires to recompile the effect.
  34712. */
  34713. ImageProcessingConfiguration.prototype._updateParameters = function () {
  34714. this.onUpdateParameters.notifyObservers(this);
  34715. };
  34716. ImageProcessingConfiguration.prototype.getClassName = function () {
  34717. return "ImageProcessingConfiguration";
  34718. };
  34719. /**
  34720. * Prepare the list of uniforms associated with the Image Processing effects.
  34721. * @param uniformsList The list of uniforms used in the effect
  34722. * @param defines the list of defines currently in use
  34723. */
  34724. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  34725. if (defines.EXPOSURE) {
  34726. uniforms.push("exposureLinear");
  34727. }
  34728. if (defines.CONTRAST) {
  34729. uniforms.push("contrast");
  34730. }
  34731. if (defines.COLORGRADING) {
  34732. uniforms.push("colorTransformSettings");
  34733. }
  34734. if (defines.VIGNETTE) {
  34735. uniforms.push("vInverseScreenSize");
  34736. uniforms.push("vignetteSettings1");
  34737. uniforms.push("vignetteSettings2");
  34738. }
  34739. if (defines.COLORCURVES) {
  34740. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  34741. }
  34742. };
  34743. /**
  34744. * Prepare the list of samplers associated with the Image Processing effects.
  34745. * @param uniformsList The list of uniforms used in the effect
  34746. * @param defines the list of defines currently in use
  34747. */
  34748. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  34749. if (defines.COLORGRADING) {
  34750. samplersList.push("txColorTransform");
  34751. }
  34752. };
  34753. /**
  34754. * Prepare the list of defines associated to the shader.
  34755. * @param defines the list of defines to complete
  34756. */
  34757. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  34758. if (forPostProcess === void 0) { forPostProcess = false; }
  34759. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  34760. defines.VIGNETTE = false;
  34761. defines.TONEMAPPING = false;
  34762. defines.CONTRAST = false;
  34763. defines.EXPOSURE = false;
  34764. defines.COLORCURVES = false;
  34765. defines.COLORGRADING = false;
  34766. defines.COLORGRADING3D = false;
  34767. defines.IMAGEPROCESSING = false;
  34768. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  34769. return;
  34770. }
  34771. defines.VIGNETTE = this.vignetteEnabled;
  34772. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  34773. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  34774. defines.TONEMAPPING = this.toneMappingEnabled;
  34775. defines.CONTRAST = (this.contrast !== 1.0);
  34776. defines.EXPOSURE = (this.exposure !== 1.0);
  34777. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  34778. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  34779. if (defines.COLORGRADING) {
  34780. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  34781. }
  34782. else {
  34783. defines.COLORGRADING3D = false;
  34784. }
  34785. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  34786. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  34787. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  34788. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  34789. };
  34790. /**
  34791. * Returns true if all the image processing information are ready.
  34792. */
  34793. ImageProcessingConfiguration.prototype.isReady = function () {
  34794. // Color Grading texure can not be none blocking.
  34795. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  34796. };
  34797. /**
  34798. * Binds the image processing to the shader.
  34799. * @param effect The effect to bind to
  34800. */
  34801. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  34802. if (aspectRatio === void 0) { aspectRatio = 1; }
  34803. // Color Curves
  34804. if (this._colorCurvesEnabled && this.colorCurves) {
  34805. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  34806. }
  34807. // Vignette
  34808. if (this._vignetteEnabled) {
  34809. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  34810. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  34811. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  34812. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  34813. var vignetteScaleX = vignetteScaleY * aspectRatio;
  34814. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  34815. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  34816. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  34817. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  34818. var vignettePower = -2.0 * this.vignetteWeight;
  34819. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  34820. }
  34821. // Exposure
  34822. effect.setFloat("exposureLinear", this.exposure);
  34823. // Contrast
  34824. effect.setFloat("contrast", this.contrast);
  34825. // Color transform settings
  34826. if (this.colorGradingTexture) {
  34827. effect.setTexture("txColorTransform", this.colorGradingTexture);
  34828. var textureSize = this.colorGradingTexture.getSize().height;
  34829. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  34830. 0.5 / textureSize, // textureOffset
  34831. textureSize, // textureSize
  34832. this.colorGradingTexture.level // weight
  34833. );
  34834. }
  34835. };
  34836. /**
  34837. * Clones the current image processing instance.
  34838. * @return The cloned image processing
  34839. */
  34840. ImageProcessingConfiguration.prototype.clone = function () {
  34841. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  34842. };
  34843. /**
  34844. * Serializes the current image processing instance to a json representation.
  34845. * @return a JSON representation
  34846. */
  34847. ImageProcessingConfiguration.prototype.serialize = function () {
  34848. return BABYLON.SerializationHelper.Serialize(this);
  34849. };
  34850. /**
  34851. * Parses the image processing from a json representation.
  34852. * @param source the JSON source to parse
  34853. * @return The parsed image processing
  34854. */
  34855. ImageProcessingConfiguration.Parse = function (source) {
  34856. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  34857. };
  34858. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  34859. /**
  34860. * Used to apply the vignette as a mix with the pixel color.
  34861. */
  34862. get: function () {
  34863. return this._VIGNETTEMODE_MULTIPLY;
  34864. },
  34865. enumerable: true,
  34866. configurable: true
  34867. });
  34868. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  34869. /**
  34870. * Used to apply the vignette as a replacement of the pixel color.
  34871. */
  34872. get: function () {
  34873. return this._VIGNETTEMODE_OPAQUE;
  34874. },
  34875. enumerable: true,
  34876. configurable: true
  34877. });
  34878. // Static constants associated to the image processing.
  34879. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  34880. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  34881. __decorate([
  34882. BABYLON.serializeAsColorCurves()
  34883. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  34884. __decorate([
  34885. BABYLON.serialize()
  34886. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  34887. __decorate([
  34888. BABYLON.serializeAsTexture()
  34889. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  34890. __decorate([
  34891. BABYLON.serialize()
  34892. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  34893. __decorate([
  34894. BABYLON.serialize()
  34895. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  34896. __decorate([
  34897. BABYLON.serialize()
  34898. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  34899. __decorate([
  34900. BABYLON.serialize()
  34901. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  34902. __decorate([
  34903. BABYLON.serialize()
  34904. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  34905. __decorate([
  34906. BABYLON.serialize()
  34907. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  34908. __decorate([
  34909. BABYLON.serialize()
  34910. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  34911. __decorate([
  34912. BABYLON.serialize()
  34913. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  34914. __decorate([
  34915. BABYLON.serialize()
  34916. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  34917. __decorate([
  34918. BABYLON.serialize()
  34919. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  34920. __decorate([
  34921. BABYLON.serializeAsColor4()
  34922. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  34923. __decorate([
  34924. BABYLON.serialize()
  34925. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  34926. __decorate([
  34927. BABYLON.serialize()
  34928. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  34929. __decorate([
  34930. BABYLON.serialize()
  34931. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  34932. __decorate([
  34933. BABYLON.serialize()
  34934. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  34935. __decorate([
  34936. BABYLON.serialize()
  34937. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  34938. return ImageProcessingConfiguration;
  34939. }());
  34940. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  34941. })(BABYLON || (BABYLON = {}));
  34942. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  34943. var BABYLON;
  34944. (function (BABYLON) {
  34945. /**
  34946. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  34947. * It can help converting any input color in a desired output one. This can then be used to create effects
  34948. * from sepia, black and white to sixties or futuristic rendering...
  34949. *
  34950. * The only supported format is currently 3dl.
  34951. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  34952. */
  34953. var ColorGradingTexture = /** @class */ (function (_super) {
  34954. __extends(ColorGradingTexture, _super);
  34955. /**
  34956. * Instantiates a ColorGradingTexture from the following parameters.
  34957. *
  34958. * @param url The location of the color gradind data (currently only supporting 3dl)
  34959. * @param scene The scene the texture will be used in
  34960. */
  34961. function ColorGradingTexture(url, scene) {
  34962. var _this = _super.call(this, scene) || this;
  34963. if (!url) {
  34964. return _this;
  34965. }
  34966. _this._engine = scene.getEngine();
  34967. _this._textureMatrix = BABYLON.Matrix.Identity();
  34968. _this.name = url;
  34969. _this.url = url;
  34970. _this.hasAlpha = false;
  34971. _this.isCube = false;
  34972. _this.is3D = _this._engine.webGLVersion > 1;
  34973. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34974. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34975. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34976. _this.anisotropicFilteringLevel = 1;
  34977. _this._texture = _this._getFromCache(url, true);
  34978. if (!_this._texture) {
  34979. if (!scene.useDelayedTextureLoading) {
  34980. _this.loadTexture();
  34981. }
  34982. else {
  34983. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34984. }
  34985. }
  34986. return _this;
  34987. }
  34988. /**
  34989. * Returns the texture matrix used in most of the material.
  34990. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  34991. */
  34992. ColorGradingTexture.prototype.getTextureMatrix = function () {
  34993. return this._textureMatrix;
  34994. };
  34995. /**
  34996. * Occurs when the file being loaded is a .3dl LUT file.
  34997. */
  34998. ColorGradingTexture.prototype.load3dlTexture = function () {
  34999. var engine = this._engine;
  35000. var texture;
  35001. if (engine.webGLVersion === 1) {
  35002. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35003. }
  35004. else {
  35005. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35006. }
  35007. this._texture = texture;
  35008. var callback = function (text) {
  35009. if (typeof text !== "string") {
  35010. return;
  35011. }
  35012. var data = null;
  35013. var tempData = null;
  35014. var line;
  35015. var lines = text.split('\n');
  35016. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35017. var maxColor = 0;
  35018. for (var i = 0; i < lines.length; i++) {
  35019. line = lines[i];
  35020. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35021. continue;
  35022. if (line.indexOf('#') === 0)
  35023. continue;
  35024. var words = line.split(" ");
  35025. if (size === 0) {
  35026. // Number of space + one
  35027. size = words.length;
  35028. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35029. tempData = new Float32Array(size * size * size * 4);
  35030. continue;
  35031. }
  35032. if (size != 0) {
  35033. var r = Math.max(parseInt(words[0]), 0);
  35034. var g = Math.max(parseInt(words[1]), 0);
  35035. var b = Math.max(parseInt(words[2]), 0);
  35036. maxColor = Math.max(r, maxColor);
  35037. maxColor = Math.max(g, maxColor);
  35038. maxColor = Math.max(b, maxColor);
  35039. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35040. if (tempData) {
  35041. tempData[pixelStorageIndex + 0] = r;
  35042. tempData[pixelStorageIndex + 1] = g;
  35043. tempData[pixelStorageIndex + 2] = b;
  35044. }
  35045. pixelIndexSlice++;
  35046. if (pixelIndexSlice % size == 0) {
  35047. pixelIndexH++;
  35048. pixelIndexSlice = 0;
  35049. if (pixelIndexH % size == 0) {
  35050. pixelIndexW++;
  35051. pixelIndexH = 0;
  35052. }
  35053. }
  35054. }
  35055. }
  35056. if (tempData && data) {
  35057. for (var i = 0; i < tempData.length; i++) {
  35058. if (i > 0 && (i + 1) % 4 === 0) {
  35059. data[i] = 255;
  35060. }
  35061. else {
  35062. var value = tempData[i];
  35063. data[i] = (value / maxColor * 255);
  35064. }
  35065. }
  35066. }
  35067. if (texture.is3D) {
  35068. texture.updateSize(size, size, size);
  35069. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35070. }
  35071. else {
  35072. texture.updateSize(size * size, size);
  35073. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35074. }
  35075. };
  35076. var scene = this.getScene();
  35077. if (scene) {
  35078. scene._loadFile(this.url, callback);
  35079. }
  35080. else {
  35081. this._engine._loadFile(this.url, callback);
  35082. }
  35083. return this._texture;
  35084. };
  35085. /**
  35086. * Starts the loading process of the texture.
  35087. */
  35088. ColorGradingTexture.prototype.loadTexture = function () {
  35089. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35090. this.load3dlTexture();
  35091. }
  35092. };
  35093. /**
  35094. * Clones the color gradind texture.
  35095. */
  35096. ColorGradingTexture.prototype.clone = function () {
  35097. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35098. // Base texture
  35099. newTexture.level = this.level;
  35100. return newTexture;
  35101. };
  35102. /**
  35103. * Called during delayed load for textures.
  35104. */
  35105. ColorGradingTexture.prototype.delayLoad = function () {
  35106. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35107. return;
  35108. }
  35109. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35110. this._texture = this._getFromCache(this.url, true);
  35111. if (!this._texture) {
  35112. this.loadTexture();
  35113. }
  35114. };
  35115. /**
  35116. * Parses a color grading texture serialized by Babylon.
  35117. * @param parsedTexture The texture information being parsedTexture
  35118. * @param scene The scene to load the texture in
  35119. * @param rootUrl The root url of the data assets to load
  35120. * @return A color gradind texture
  35121. */
  35122. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35123. var texture = null;
  35124. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35125. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35126. texture.name = parsedTexture.name;
  35127. texture.level = parsedTexture.level;
  35128. }
  35129. return texture;
  35130. };
  35131. /**
  35132. * Serializes the LUT texture to json format.
  35133. */
  35134. ColorGradingTexture.prototype.serialize = function () {
  35135. if (!this.name) {
  35136. return null;
  35137. }
  35138. var serializationObject = {};
  35139. serializationObject.name = this.name;
  35140. serializationObject.level = this.level;
  35141. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35142. return serializationObject;
  35143. };
  35144. /**
  35145. * Empty line regex stored for GC.
  35146. */
  35147. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35148. return ColorGradingTexture;
  35149. }(BABYLON.BaseTexture));
  35150. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35151. })(BABYLON || (BABYLON = {}));
  35152. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35153. var BABYLON;
  35154. (function (BABYLON) {
  35155. /**
  35156. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35157. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35158. * 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;
  35159. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35160. */
  35161. var ColorCurves = /** @class */ (function () {
  35162. function ColorCurves() {
  35163. this._dirty = true;
  35164. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35165. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35166. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35167. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35168. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35169. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35170. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35171. this._globalHue = 30;
  35172. this._globalDensity = 0;
  35173. this._globalSaturation = 0;
  35174. this._globalExposure = 0;
  35175. this._highlightsHue = 30;
  35176. this._highlightsDensity = 0;
  35177. this._highlightsSaturation = 0;
  35178. this._highlightsExposure = 0;
  35179. this._midtonesHue = 30;
  35180. this._midtonesDensity = 0;
  35181. this._midtonesSaturation = 0;
  35182. this._midtonesExposure = 0;
  35183. this._shadowsHue = 30;
  35184. this._shadowsDensity = 0;
  35185. this._shadowsSaturation = 0;
  35186. this._shadowsExposure = 0;
  35187. }
  35188. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35189. /**
  35190. * Gets the global Hue value.
  35191. * 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).
  35192. */
  35193. get: function () {
  35194. return this._globalHue;
  35195. },
  35196. /**
  35197. * Sets the global Hue value.
  35198. * 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).
  35199. */
  35200. set: function (value) {
  35201. this._globalHue = value;
  35202. this._dirty = true;
  35203. },
  35204. enumerable: true,
  35205. configurable: true
  35206. });
  35207. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35208. /**
  35209. * Gets the global Density value.
  35210. * 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.
  35211. * Values less than zero provide a filter of opposite hue.
  35212. */
  35213. get: function () {
  35214. return this._globalDensity;
  35215. },
  35216. /**
  35217. * Sets the global Density value.
  35218. * 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.
  35219. * Values less than zero provide a filter of opposite hue.
  35220. */
  35221. set: function (value) {
  35222. this._globalDensity = value;
  35223. this._dirty = true;
  35224. },
  35225. enumerable: true,
  35226. configurable: true
  35227. });
  35228. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35229. /**
  35230. * Gets the global Saturation value.
  35231. * 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.
  35232. */
  35233. get: function () {
  35234. return this._globalSaturation;
  35235. },
  35236. /**
  35237. * Sets the global Saturation value.
  35238. * 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.
  35239. */
  35240. set: function (value) {
  35241. this._globalSaturation = value;
  35242. this._dirty = true;
  35243. },
  35244. enumerable: true,
  35245. configurable: true
  35246. });
  35247. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35248. /**
  35249. * Gets the highlights Hue value.
  35250. * 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).
  35251. */
  35252. get: function () {
  35253. return this._highlightsHue;
  35254. },
  35255. /**
  35256. * Sets the highlights Hue value.
  35257. * 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).
  35258. */
  35259. set: function (value) {
  35260. this._highlightsHue = value;
  35261. this._dirty = true;
  35262. },
  35263. enumerable: true,
  35264. configurable: true
  35265. });
  35266. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35267. /**
  35268. * Gets the highlights Density value.
  35269. * 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.
  35270. * Values less than zero provide a filter of opposite hue.
  35271. */
  35272. get: function () {
  35273. return this._highlightsDensity;
  35274. },
  35275. /**
  35276. * Sets the highlights Density value.
  35277. * 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.
  35278. * Values less than zero provide a filter of opposite hue.
  35279. */
  35280. set: function (value) {
  35281. this._highlightsDensity = value;
  35282. this._dirty = true;
  35283. },
  35284. enumerable: true,
  35285. configurable: true
  35286. });
  35287. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35288. /**
  35289. * Gets the highlights Saturation value.
  35290. * 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.
  35291. */
  35292. get: function () {
  35293. return this._highlightsSaturation;
  35294. },
  35295. /**
  35296. * Sets the highlights Saturation value.
  35297. * 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.
  35298. */
  35299. set: function (value) {
  35300. this._highlightsSaturation = value;
  35301. this._dirty = true;
  35302. },
  35303. enumerable: true,
  35304. configurable: true
  35305. });
  35306. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35307. /**
  35308. * Gets the highlights Exposure value.
  35309. * 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.
  35310. */
  35311. get: function () {
  35312. return this._highlightsExposure;
  35313. },
  35314. /**
  35315. * Sets the highlights Exposure value.
  35316. * 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.
  35317. */
  35318. set: function (value) {
  35319. this._highlightsExposure = value;
  35320. this._dirty = true;
  35321. },
  35322. enumerable: true,
  35323. configurable: true
  35324. });
  35325. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35326. /**
  35327. * Gets the midtones Hue value.
  35328. * 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).
  35329. */
  35330. get: function () {
  35331. return this._midtonesHue;
  35332. },
  35333. /**
  35334. * Sets the midtones Hue value.
  35335. * 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).
  35336. */
  35337. set: function (value) {
  35338. this._midtonesHue = value;
  35339. this._dirty = true;
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35345. /**
  35346. * Gets the midtones Density value.
  35347. * 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.
  35348. * Values less than zero provide a filter of opposite hue.
  35349. */
  35350. get: function () {
  35351. return this._midtonesDensity;
  35352. },
  35353. /**
  35354. * Sets the midtones Density value.
  35355. * 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.
  35356. * Values less than zero provide a filter of opposite hue.
  35357. */
  35358. set: function (value) {
  35359. this._midtonesDensity = value;
  35360. this._dirty = true;
  35361. },
  35362. enumerable: true,
  35363. configurable: true
  35364. });
  35365. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35366. /**
  35367. * Gets the midtones Saturation value.
  35368. * 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.
  35369. */
  35370. get: function () {
  35371. return this._midtonesSaturation;
  35372. },
  35373. /**
  35374. * Sets the midtones Saturation value.
  35375. * 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.
  35376. */
  35377. set: function (value) {
  35378. this._midtonesSaturation = value;
  35379. this._dirty = true;
  35380. },
  35381. enumerable: true,
  35382. configurable: true
  35383. });
  35384. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35385. /**
  35386. * Gets the midtones Exposure value.
  35387. * 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.
  35388. */
  35389. get: function () {
  35390. return this._midtonesExposure;
  35391. },
  35392. /**
  35393. * Sets the midtones Exposure value.
  35394. * 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.
  35395. */
  35396. set: function (value) {
  35397. this._midtonesExposure = value;
  35398. this._dirty = true;
  35399. },
  35400. enumerable: true,
  35401. configurable: true
  35402. });
  35403. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35404. /**
  35405. * Gets the shadows Hue value.
  35406. * 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).
  35407. */
  35408. get: function () {
  35409. return this._shadowsHue;
  35410. },
  35411. /**
  35412. * Sets the shadows Hue value.
  35413. * 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).
  35414. */
  35415. set: function (value) {
  35416. this._shadowsHue = value;
  35417. this._dirty = true;
  35418. },
  35419. enumerable: true,
  35420. configurable: true
  35421. });
  35422. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35423. /**
  35424. * Gets the shadows Density value.
  35425. * 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.
  35426. * Values less than zero provide a filter of opposite hue.
  35427. */
  35428. get: function () {
  35429. return this._shadowsDensity;
  35430. },
  35431. /**
  35432. * Sets the shadows Density value.
  35433. * 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.
  35434. * Values less than zero provide a filter of opposite hue.
  35435. */
  35436. set: function (value) {
  35437. this._shadowsDensity = value;
  35438. this._dirty = true;
  35439. },
  35440. enumerable: true,
  35441. configurable: true
  35442. });
  35443. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35444. /**
  35445. * Gets the shadows Saturation value.
  35446. * 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.
  35447. */
  35448. get: function () {
  35449. return this._shadowsSaturation;
  35450. },
  35451. /**
  35452. * Sets the shadows Saturation value.
  35453. * 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.
  35454. */
  35455. set: function (value) {
  35456. this._shadowsSaturation = value;
  35457. this._dirty = true;
  35458. },
  35459. enumerable: true,
  35460. configurable: true
  35461. });
  35462. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35463. /**
  35464. * Gets the shadows Exposure value.
  35465. * 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.
  35466. */
  35467. get: function () {
  35468. return this._shadowsExposure;
  35469. },
  35470. /**
  35471. * Sets the shadows Exposure value.
  35472. * 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.
  35473. */
  35474. set: function (value) {
  35475. this._shadowsExposure = value;
  35476. this._dirty = true;
  35477. },
  35478. enumerable: true,
  35479. configurable: true
  35480. });
  35481. ColorCurves.prototype.getClassName = function () {
  35482. return "ColorCurves";
  35483. };
  35484. /**
  35485. * Binds the color curves to the shader.
  35486. * @param colorCurves The color curve to bind
  35487. * @param effect The effect to bind to
  35488. */
  35489. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35490. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35491. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35492. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35493. if (colorCurves._dirty) {
  35494. colorCurves._dirty = false;
  35495. // Fill in global info.
  35496. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35497. // Compute highlights info.
  35498. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35499. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35500. // Compute midtones info.
  35501. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35502. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35503. // Compute shadows info.
  35504. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35505. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35506. // Compute deltas (neutral is midtones).
  35507. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35508. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35509. }
  35510. if (effect) {
  35511. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35512. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35513. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35514. }
  35515. };
  35516. /**
  35517. * Prepare the list of uniforms associated with the ColorCurves effects.
  35518. * @param uniformsList The list of uniforms used in the effect
  35519. */
  35520. ColorCurves.PrepareUniforms = function (uniformsList) {
  35521. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35522. };
  35523. /**
  35524. * Returns color grading data based on a hue, density, saturation and exposure value.
  35525. * @param filterHue The hue of the color filter.
  35526. * @param filterDensity The density of the color filter.
  35527. * @param saturation The saturation.
  35528. * @param exposure The exposure.
  35529. * @param result The result data container.
  35530. */
  35531. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35532. if (hue == null) {
  35533. return;
  35534. }
  35535. hue = ColorCurves.clamp(hue, 0, 360);
  35536. density = ColorCurves.clamp(density, -100, 100);
  35537. saturation = ColorCurves.clamp(saturation, -100, 100);
  35538. exposure = ColorCurves.clamp(exposure, -100, 100);
  35539. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35540. // so that the maximum filter density is only 50% control. This provides fine control
  35541. // for small values and reasonable range.
  35542. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35543. density *= 0.5;
  35544. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35545. if (density < 0) {
  35546. density *= -1;
  35547. hue = (hue + 180) % 360;
  35548. }
  35549. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35550. result.scaleToRef(2, result);
  35551. result.a = 1 + 0.01 * saturation;
  35552. };
  35553. /**
  35554. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35555. * @param value The input slider value in range [-100,100].
  35556. * @returns Adjusted value.
  35557. */
  35558. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35559. value /= 100;
  35560. var x = Math.abs(value);
  35561. x = Math.pow(x, 2);
  35562. if (value < 0) {
  35563. x *= -1;
  35564. }
  35565. x *= 100;
  35566. return x;
  35567. };
  35568. /**
  35569. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35570. * @param hue The hue (H) input.
  35571. * @param saturation The saturation (S) input.
  35572. * @param brightness The brightness (B) input.
  35573. * @result An RGBA color represented as Vector4.
  35574. */
  35575. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35576. var h = ColorCurves.clamp(hue, 0, 360);
  35577. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35578. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35579. if (s === 0) {
  35580. result.r = v;
  35581. result.g = v;
  35582. result.b = v;
  35583. }
  35584. else {
  35585. // sector 0 to 5
  35586. h /= 60;
  35587. var i = Math.floor(h);
  35588. // fractional part of h
  35589. var f = h - i;
  35590. var p = v * (1 - s);
  35591. var q = v * (1 - s * f);
  35592. var t = v * (1 - s * (1 - f));
  35593. switch (i) {
  35594. case 0:
  35595. result.r = v;
  35596. result.g = t;
  35597. result.b = p;
  35598. break;
  35599. case 1:
  35600. result.r = q;
  35601. result.g = v;
  35602. result.b = p;
  35603. break;
  35604. case 2:
  35605. result.r = p;
  35606. result.g = v;
  35607. result.b = t;
  35608. break;
  35609. case 3:
  35610. result.r = p;
  35611. result.g = q;
  35612. result.b = v;
  35613. break;
  35614. case 4:
  35615. result.r = t;
  35616. result.g = p;
  35617. result.b = v;
  35618. break;
  35619. default:// case 5:
  35620. result.r = v;
  35621. result.g = p;
  35622. result.b = q;
  35623. break;
  35624. }
  35625. }
  35626. result.a = 1;
  35627. };
  35628. /**
  35629. * Returns a value clamped between min and max
  35630. * @param value The value to clamp
  35631. * @param min The minimum of value
  35632. * @param max The maximum of value
  35633. * @returns The clamped value.
  35634. */
  35635. ColorCurves.clamp = function (value, min, max) {
  35636. return Math.min(Math.max(value, min), max);
  35637. };
  35638. /**
  35639. * Clones the current color curve instance.
  35640. * @return The cloned curves
  35641. */
  35642. ColorCurves.prototype.clone = function () {
  35643. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35644. };
  35645. /**
  35646. * Serializes the current color curve instance to a json representation.
  35647. * @return a JSON representation
  35648. */
  35649. ColorCurves.prototype.serialize = function () {
  35650. return BABYLON.SerializationHelper.Serialize(this);
  35651. };
  35652. /**
  35653. * Parses the color curve from a json representation.
  35654. * @param source the JSON source to parse
  35655. * @return The parsed curves
  35656. */
  35657. ColorCurves.Parse = function (source) {
  35658. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35659. };
  35660. __decorate([
  35661. BABYLON.serialize()
  35662. ], ColorCurves.prototype, "_globalHue", void 0);
  35663. __decorate([
  35664. BABYLON.serialize()
  35665. ], ColorCurves.prototype, "_globalDensity", void 0);
  35666. __decorate([
  35667. BABYLON.serialize()
  35668. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35669. __decorate([
  35670. BABYLON.serialize()
  35671. ], ColorCurves.prototype, "_globalExposure", void 0);
  35672. __decorate([
  35673. BABYLON.serialize()
  35674. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35675. __decorate([
  35676. BABYLON.serialize()
  35677. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35678. __decorate([
  35679. BABYLON.serialize()
  35680. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35681. __decorate([
  35682. BABYLON.serialize()
  35683. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35684. __decorate([
  35685. BABYLON.serialize()
  35686. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35687. __decorate([
  35688. BABYLON.serialize()
  35689. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35690. __decorate([
  35691. BABYLON.serialize()
  35692. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35693. __decorate([
  35694. BABYLON.serialize()
  35695. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  35696. return ColorCurves;
  35697. }());
  35698. BABYLON.ColorCurves = ColorCurves;
  35699. })(BABYLON || (BABYLON = {}));
  35700. //# sourceMappingURL=babylon.colorCurves.js.map
  35701. //# sourceMappingURL=babylon.behavior.js.map
  35702. var BABYLON;
  35703. (function (BABYLON) {
  35704. var MaterialHelper = /** @class */ (function () {
  35705. function MaterialHelper() {
  35706. }
  35707. MaterialHelper.BindEyePosition = function (effect, scene) {
  35708. if (scene._forcedViewPosition) {
  35709. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35710. return;
  35711. }
  35712. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35713. };
  35714. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  35715. defines._needUVs = true;
  35716. defines[key] = true;
  35717. if (texture.getTextureMatrix().isIdentity(true)) {
  35718. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  35719. if (texture.coordinatesIndex === 0) {
  35720. defines["MAINUV1"] = true;
  35721. }
  35722. else {
  35723. defines["MAINUV2"] = true;
  35724. }
  35725. }
  35726. else {
  35727. defines[key + "DIRECTUV"] = 0;
  35728. }
  35729. };
  35730. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  35731. var matrix = texture.getTextureMatrix();
  35732. if (!matrix.isIdentity(true)) {
  35733. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  35734. }
  35735. };
  35736. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  35737. if (defines._areMiscDirty) {
  35738. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  35739. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  35740. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  35741. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  35742. }
  35743. };
  35744. /**
  35745. * Helper used to prepare the list of defines for shader compilation
  35746. * @param scene defines the current scene
  35747. * @param engine defines the current engine
  35748. * @param defines specifies the list of active defines
  35749. * @param useInstances defines if instances have to be turned on
  35750. * @param alphaTest defines if alpha testing has to be turned on
  35751. */
  35752. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  35753. var changed = false;
  35754. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  35755. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  35756. changed = true;
  35757. }
  35758. if (defines["ALPHATEST"] !== alphaTest) {
  35759. defines["ALPHATEST"] = !defines["ALPHATEST"];
  35760. changed = true;
  35761. }
  35762. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  35763. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  35764. changed = true;
  35765. }
  35766. if (defines["INSTANCES"] !== useInstances) {
  35767. defines["INSTANCES"] = useInstances;
  35768. changed = true;
  35769. }
  35770. if (changed) {
  35771. defines.markAsUnprocessed();
  35772. }
  35773. };
  35774. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  35775. if (useMorphTargets === void 0) { useMorphTargets = false; }
  35776. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  35777. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  35778. return false;
  35779. }
  35780. defines._normals = defines._needNormals;
  35781. defines._uvs = defines._needUVs;
  35782. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  35783. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35784. defines["TANGENT"] = true;
  35785. }
  35786. if (defines._needUVs) {
  35787. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  35788. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  35789. }
  35790. else {
  35791. defines["UV1"] = false;
  35792. defines["UV2"] = false;
  35793. }
  35794. if (useVertexColor) {
  35795. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  35796. defines["VERTEXCOLOR"] = hasVertexColors;
  35797. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  35798. }
  35799. if (useBones) {
  35800. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35801. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  35802. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  35803. }
  35804. else {
  35805. defines["NUM_BONE_INFLUENCERS"] = 0;
  35806. defines["BonesPerMesh"] = 0;
  35807. }
  35808. }
  35809. if (useMorphTargets) {
  35810. var manager = mesh.morphTargetManager;
  35811. if (manager) {
  35812. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  35813. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  35814. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  35815. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  35816. }
  35817. else {
  35818. defines["MORPHTARGETS_TANGENT"] = false;
  35819. defines["MORPHTARGETS_NORMAL"] = false;
  35820. defines["MORPHTARGETS"] = false;
  35821. defines["NUM_MORPH_INFLUENCERS"] = 0;
  35822. }
  35823. }
  35824. return true;
  35825. };
  35826. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  35827. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35828. if (disableLighting === void 0) { disableLighting = false; }
  35829. if (!defines._areLightsDirty) {
  35830. return defines._needNormals;
  35831. }
  35832. var lightIndex = 0;
  35833. var needNormals = false;
  35834. var needRebuild = false;
  35835. var lightmapMode = false;
  35836. var shadowEnabled = false;
  35837. var specularEnabled = false;
  35838. if (scene.lightsEnabled && !disableLighting) {
  35839. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  35840. var light = _a[_i];
  35841. needNormals = true;
  35842. if (defines["LIGHT" + lightIndex] === undefined) {
  35843. needRebuild = true;
  35844. }
  35845. defines["LIGHT" + lightIndex] = true;
  35846. defines["SPOTLIGHT" + lightIndex] = false;
  35847. defines["HEMILIGHT" + lightIndex] = false;
  35848. defines["POINTLIGHT" + lightIndex] = false;
  35849. defines["DIRLIGHT" + lightIndex] = false;
  35850. var type;
  35851. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  35852. type = "SPOTLIGHT" + lightIndex;
  35853. }
  35854. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  35855. type = "HEMILIGHT" + lightIndex;
  35856. }
  35857. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  35858. type = "POINTLIGHT" + lightIndex;
  35859. }
  35860. else {
  35861. type = "DIRLIGHT" + lightIndex;
  35862. }
  35863. defines[type] = true;
  35864. // Specular
  35865. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  35866. specularEnabled = true;
  35867. }
  35868. // Shadows
  35869. defines["SHADOW" + lightIndex] = false;
  35870. defines["SHADOWPCF" + lightIndex] = false;
  35871. defines["SHADOWESM" + lightIndex] = false;
  35872. defines["SHADOWCUBE" + lightIndex] = false;
  35873. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  35874. var shadowGenerator = light.getShadowGenerator();
  35875. if (shadowGenerator) {
  35876. shadowEnabled = true;
  35877. shadowGenerator.prepareDefines(defines, lightIndex);
  35878. }
  35879. }
  35880. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  35881. lightmapMode = true;
  35882. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  35883. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  35884. }
  35885. else {
  35886. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  35887. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  35888. }
  35889. lightIndex++;
  35890. if (lightIndex === maxSimultaneousLights)
  35891. break;
  35892. }
  35893. }
  35894. defines["SPECULARTERM"] = specularEnabled;
  35895. defines["SHADOWS"] = shadowEnabled;
  35896. // Resetting all other lights if any
  35897. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  35898. if (defines["LIGHT" + index] !== undefined) {
  35899. defines["LIGHT" + index] = false;
  35900. defines["HEMILIGHT" + lightIndex] = false;
  35901. defines["POINTLIGHT" + lightIndex] = false;
  35902. defines["DIRLIGHT" + lightIndex] = false;
  35903. defines["SPOTLIGHT" + lightIndex] = false;
  35904. defines["SHADOW" + lightIndex] = false;
  35905. }
  35906. }
  35907. var caps = scene.getEngine().getCaps();
  35908. if (defines["SHADOWFLOAT"] === undefined) {
  35909. needRebuild = true;
  35910. }
  35911. defines["SHADOWFLOAT"] = shadowEnabled &&
  35912. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  35913. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  35914. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  35915. if (needRebuild) {
  35916. defines.rebuild();
  35917. }
  35918. return needNormals;
  35919. };
  35920. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  35921. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35922. var uniformsList;
  35923. var uniformBuffersList = null;
  35924. if (uniformsListOrOptions.uniformsNames) {
  35925. var options = uniformsListOrOptions;
  35926. uniformsList = options.uniformsNames;
  35927. uniformBuffersList = options.uniformBuffersNames;
  35928. samplersList = options.samplers;
  35929. defines = options.defines;
  35930. maxSimultaneousLights = options.maxSimultaneousLights;
  35931. }
  35932. else {
  35933. uniformsList = uniformsListOrOptions;
  35934. if (!samplersList) {
  35935. samplersList = [];
  35936. }
  35937. }
  35938. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35939. if (!defines["LIGHT" + lightIndex]) {
  35940. break;
  35941. }
  35942. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  35943. if (uniformBuffersList) {
  35944. uniformBuffersList.push("Light" + lightIndex);
  35945. }
  35946. samplersList.push("shadowSampler" + lightIndex);
  35947. }
  35948. if (defines["NUM_MORPH_INFLUENCERS"]) {
  35949. uniformsList.push("morphTargetInfluences");
  35950. }
  35951. };
  35952. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  35953. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35954. if (rank === void 0) { rank = 0; }
  35955. var lightFallbackRank = 0;
  35956. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  35957. if (!defines["LIGHT" + lightIndex]) {
  35958. break;
  35959. }
  35960. if (lightIndex > 0) {
  35961. lightFallbackRank = rank + lightIndex;
  35962. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  35963. }
  35964. if (!defines["SHADOWS"]) {
  35965. if (defines["SHADOW" + lightIndex]) {
  35966. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  35967. }
  35968. if (defines["SHADOWPCF" + lightIndex]) {
  35969. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  35970. }
  35971. if (defines["SHADOWESM" + lightIndex]) {
  35972. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  35973. }
  35974. }
  35975. }
  35976. return lightFallbackRank++;
  35977. };
  35978. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  35979. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  35980. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  35981. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  35982. var manager = mesh.morphTargetManager;
  35983. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  35984. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  35985. for (var index = 0; index < influencers; index++) {
  35986. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  35987. if (normal) {
  35988. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  35989. }
  35990. if (tangent) {
  35991. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  35992. }
  35993. if (attribs.length > maxAttributesCount) {
  35994. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  35995. }
  35996. }
  35997. }
  35998. };
  35999. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36000. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36001. fallbacks.addCPUSkinningFallback(0, mesh);
  36002. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36003. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36004. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36007. }
  36008. }
  36009. };
  36010. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36011. if (defines["INSTANCES"]) {
  36012. attribs.push("world0");
  36013. attribs.push("world1");
  36014. attribs.push("world2");
  36015. attribs.push("world3");
  36016. }
  36017. };
  36018. // Bindings
  36019. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36020. if (light.shadowEnabled && mesh.receiveShadows) {
  36021. var shadowGenerator = light.getShadowGenerator();
  36022. if (shadowGenerator) {
  36023. shadowGenerator.bindShadowLight(lightIndex, effect);
  36024. }
  36025. }
  36026. };
  36027. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36028. light.transferToEffect(effect, lightIndex + "");
  36029. };
  36030. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36031. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36032. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36033. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36034. for (var i = 0; i < len; i++) {
  36035. var light = mesh._lightSources[i];
  36036. var iAsString = i.toString();
  36037. var scaledIntensity = light.getScaledIntensity();
  36038. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36039. MaterialHelper.BindLightProperties(light, effect, i);
  36040. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36041. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36042. if (defines["SPECULARTERM"]) {
  36043. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36044. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36045. }
  36046. // Shadows
  36047. if (scene.shadowsEnabled) {
  36048. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36049. }
  36050. light._uniformBuffer.update();
  36051. }
  36052. };
  36053. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36054. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36055. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36056. effect.setColor3("vFogColor", scene.fogColor);
  36057. }
  36058. };
  36059. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36060. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36061. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36062. if (matrices && effect) {
  36063. effect.setMatrices("mBones", matrices);
  36064. }
  36065. }
  36066. };
  36067. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36068. var manager = abstractMesh.morphTargetManager;
  36069. if (!abstractMesh || !manager) {
  36070. return;
  36071. }
  36072. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36073. };
  36074. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36075. if (defines["LOGARITHMICDEPTH"]) {
  36076. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36077. }
  36078. };
  36079. MaterialHelper.BindClipPlane = function (effect, scene) {
  36080. if (scene.clipPlane) {
  36081. var clipPlane = scene.clipPlane;
  36082. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36083. }
  36084. };
  36085. return MaterialHelper;
  36086. }());
  36087. BABYLON.MaterialHelper = MaterialHelper;
  36088. })(BABYLON || (BABYLON = {}));
  36089. //# sourceMappingURL=babylon.materialHelper.js.map
  36090. var BABYLON;
  36091. (function (BABYLON) {
  36092. var PushMaterial = /** @class */ (function (_super) {
  36093. __extends(PushMaterial, _super);
  36094. function PushMaterial(name, scene) {
  36095. var _this = _super.call(this, name, scene) || this;
  36096. _this.storeEffectOnSubMeshes = true;
  36097. return _this;
  36098. }
  36099. PushMaterial.prototype.getEffect = function () {
  36100. return this._activeEffect;
  36101. };
  36102. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36103. if (!mesh) {
  36104. return false;
  36105. }
  36106. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36107. return true;
  36108. }
  36109. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36110. };
  36111. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36112. this._activeEffect.setMatrix("world", world);
  36113. };
  36114. PushMaterial.prototype.bind = function (world, mesh) {
  36115. if (!mesh) {
  36116. return;
  36117. }
  36118. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36119. };
  36120. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36121. if (effect === void 0) { effect = null; }
  36122. _super.prototype._afterBind.call(this, mesh);
  36123. this.getScene()._cachedEffect = effect;
  36124. };
  36125. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36126. if (visibility === void 0) { visibility = 1; }
  36127. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36128. };
  36129. return PushMaterial;
  36130. }(BABYLON.Material));
  36131. BABYLON.PushMaterial = PushMaterial;
  36132. })(BABYLON || (BABYLON = {}));
  36133. //# sourceMappingURL=babylon.pushMaterial.js.map
  36134. var BABYLON;
  36135. (function (BABYLON) {
  36136. var StandardMaterialDefines = /** @class */ (function (_super) {
  36137. __extends(StandardMaterialDefines, _super);
  36138. function StandardMaterialDefines() {
  36139. var _this = _super.call(this) || this;
  36140. _this.MAINUV1 = false;
  36141. _this.MAINUV2 = false;
  36142. _this.DIFFUSE = false;
  36143. _this.DIFFUSEDIRECTUV = 0;
  36144. _this.AMBIENT = false;
  36145. _this.AMBIENTDIRECTUV = 0;
  36146. _this.OPACITY = false;
  36147. _this.OPACITYDIRECTUV = 0;
  36148. _this.OPACITYRGB = false;
  36149. _this.REFLECTION = false;
  36150. _this.EMISSIVE = false;
  36151. _this.EMISSIVEDIRECTUV = 0;
  36152. _this.SPECULAR = false;
  36153. _this.SPECULARDIRECTUV = 0;
  36154. _this.BUMP = false;
  36155. _this.BUMPDIRECTUV = 0;
  36156. _this.PARALLAX = false;
  36157. _this.PARALLAXOCCLUSION = false;
  36158. _this.SPECULAROVERALPHA = false;
  36159. _this.CLIPPLANE = false;
  36160. _this.ALPHATEST = false;
  36161. _this.DEPTHPREPASS = false;
  36162. _this.ALPHAFROMDIFFUSE = false;
  36163. _this.POINTSIZE = false;
  36164. _this.FOG = false;
  36165. _this.SPECULARTERM = false;
  36166. _this.DIFFUSEFRESNEL = false;
  36167. _this.OPACITYFRESNEL = false;
  36168. _this.REFLECTIONFRESNEL = false;
  36169. _this.REFRACTIONFRESNEL = false;
  36170. _this.EMISSIVEFRESNEL = false;
  36171. _this.FRESNEL = false;
  36172. _this.NORMAL = false;
  36173. _this.UV1 = false;
  36174. _this.UV2 = false;
  36175. _this.VERTEXCOLOR = false;
  36176. _this.VERTEXALPHA = false;
  36177. _this.NUM_BONE_INFLUENCERS = 0;
  36178. _this.BonesPerMesh = 0;
  36179. _this.INSTANCES = false;
  36180. _this.GLOSSINESS = false;
  36181. _this.ROUGHNESS = false;
  36182. _this.EMISSIVEASILLUMINATION = false;
  36183. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36184. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36185. _this.LIGHTMAP = false;
  36186. _this.LIGHTMAPDIRECTUV = 0;
  36187. _this.USELIGHTMAPASSHADOWMAP = false;
  36188. _this.REFLECTIONMAP_3D = false;
  36189. _this.REFLECTIONMAP_SPHERICAL = false;
  36190. _this.REFLECTIONMAP_PLANAR = false;
  36191. _this.REFLECTIONMAP_CUBIC = false;
  36192. _this.REFLECTIONMAP_PROJECTION = false;
  36193. _this.REFLECTIONMAP_SKYBOX = false;
  36194. _this.REFLECTIONMAP_EXPLICIT = false;
  36195. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36196. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36197. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36198. _this.INVERTCUBICMAP = false;
  36199. _this.LOGARITHMICDEPTH = false;
  36200. _this.REFRACTION = false;
  36201. _this.REFRACTIONMAP_3D = false;
  36202. _this.REFLECTIONOVERALPHA = false;
  36203. _this.TWOSIDEDLIGHTING = false;
  36204. _this.SHADOWFLOAT = false;
  36205. _this.MORPHTARGETS = false;
  36206. _this.MORPHTARGETS_NORMAL = false;
  36207. _this.MORPHTARGETS_TANGENT = false;
  36208. _this.NUM_MORPH_INFLUENCERS = 0;
  36209. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36210. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36211. _this.IMAGEPROCESSING = false;
  36212. _this.VIGNETTE = false;
  36213. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36214. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36215. _this.TONEMAPPING = false;
  36216. _this.CONTRAST = false;
  36217. _this.COLORCURVES = false;
  36218. _this.COLORGRADING = false;
  36219. _this.COLORGRADING3D = false;
  36220. _this.SAMPLER3DGREENDEPTH = false;
  36221. _this.SAMPLER3DBGRMAP = false;
  36222. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36223. _this.EXPOSURE = false;
  36224. _this.rebuild();
  36225. return _this;
  36226. }
  36227. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36228. var modes = [
  36229. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36230. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36231. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36232. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36233. ];
  36234. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36235. var mode = modes_1[_i];
  36236. this[mode] = (mode === modeToEnable);
  36237. }
  36238. };
  36239. return StandardMaterialDefines;
  36240. }(BABYLON.MaterialDefines));
  36241. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36242. var StandardMaterial = /** @class */ (function (_super) {
  36243. __extends(StandardMaterial, _super);
  36244. function StandardMaterial(name, scene) {
  36245. var _this = _super.call(this, name, scene) || this;
  36246. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36247. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36248. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36249. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36250. _this.specularPower = 64;
  36251. _this._useAlphaFromDiffuseTexture = false;
  36252. _this._useEmissiveAsIllumination = false;
  36253. _this._linkEmissiveWithDiffuse = false;
  36254. _this._useSpecularOverAlpha = false;
  36255. _this._useReflectionOverAlpha = false;
  36256. _this._disableLighting = false;
  36257. _this._useParallax = false;
  36258. _this._useParallaxOcclusion = false;
  36259. _this.parallaxScaleBias = 0.05;
  36260. _this._roughness = 0;
  36261. _this.indexOfRefraction = 0.98;
  36262. _this.invertRefractionY = true;
  36263. _this._useLightmapAsShadowmap = false;
  36264. _this._useReflectionFresnelFromSpecular = false;
  36265. _this._useGlossinessFromSpecularMapAlpha = false;
  36266. _this._maxSimultaneousLights = 4;
  36267. /**
  36268. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36269. */
  36270. _this._invertNormalMapX = false;
  36271. /**
  36272. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36273. */
  36274. _this._invertNormalMapY = false;
  36275. /**
  36276. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36277. */
  36278. _this._twoSidedLighting = false;
  36279. _this._renderTargets = new BABYLON.SmartArray(16);
  36280. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36281. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36282. // Setup the default processing configuration to the scene.
  36283. _this._attachImageProcessingConfiguration(null);
  36284. _this.getRenderTargetTextures = function () {
  36285. _this._renderTargets.reset();
  36286. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36287. _this._renderTargets.push(_this._reflectionTexture);
  36288. }
  36289. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36290. _this._renderTargets.push(_this._refractionTexture);
  36291. }
  36292. return _this._renderTargets;
  36293. };
  36294. return _this;
  36295. }
  36296. ;
  36297. ;
  36298. ;
  36299. ;
  36300. ;
  36301. ;
  36302. ;
  36303. ;
  36304. ;
  36305. ;
  36306. ;
  36307. ;
  36308. ;
  36309. ;
  36310. ;
  36311. ;
  36312. ;
  36313. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36314. /**
  36315. * Gets the image processing configuration used either in this material.
  36316. */
  36317. get: function () {
  36318. return this._imageProcessingConfiguration;
  36319. },
  36320. /**
  36321. * Sets the Default image processing configuration used either in the this material.
  36322. *
  36323. * If sets to null, the scene one is in use.
  36324. */
  36325. set: function (value) {
  36326. this._attachImageProcessingConfiguration(value);
  36327. // Ensure the effect will be rebuilt.
  36328. this._markAllSubMeshesAsTexturesDirty();
  36329. },
  36330. enumerable: true,
  36331. configurable: true
  36332. });
  36333. /**
  36334. * Attaches a new image processing configuration to the Standard Material.
  36335. * @param configuration
  36336. */
  36337. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36338. var _this = this;
  36339. if (configuration === this._imageProcessingConfiguration) {
  36340. return;
  36341. }
  36342. // Detaches observer.
  36343. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36344. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36345. }
  36346. // Pick the scene configuration if needed.
  36347. if (!configuration) {
  36348. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36349. }
  36350. else {
  36351. this._imageProcessingConfiguration = configuration;
  36352. }
  36353. // Attaches observer.
  36354. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36355. _this._markAllSubMeshesAsImageProcessingDirty();
  36356. });
  36357. };
  36358. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36359. /**
  36360. * Gets wether the color curves effect is enabled.
  36361. */
  36362. get: function () {
  36363. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36364. },
  36365. /**
  36366. * Sets wether the color curves effect is enabled.
  36367. */
  36368. set: function (value) {
  36369. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36370. },
  36371. enumerable: true,
  36372. configurable: true
  36373. });
  36374. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36375. /**
  36376. * Gets wether the color grading effect is enabled.
  36377. */
  36378. get: function () {
  36379. return this.imageProcessingConfiguration.colorGradingEnabled;
  36380. },
  36381. /**
  36382. * Gets wether the color grading effect is enabled.
  36383. */
  36384. set: function (value) {
  36385. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36386. },
  36387. enumerable: true,
  36388. configurable: true
  36389. });
  36390. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36391. /**
  36392. * Gets wether tonemapping is enabled or not.
  36393. */
  36394. get: function () {
  36395. return this._imageProcessingConfiguration.toneMappingEnabled;
  36396. },
  36397. /**
  36398. * Sets wether tonemapping is enabled or not
  36399. */
  36400. set: function (value) {
  36401. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36402. },
  36403. enumerable: true,
  36404. configurable: true
  36405. });
  36406. ;
  36407. ;
  36408. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36409. /**
  36410. * The camera exposure used on this material.
  36411. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36412. * This corresponds to a photographic exposure.
  36413. */
  36414. get: function () {
  36415. return this._imageProcessingConfiguration.exposure;
  36416. },
  36417. /**
  36418. * The camera exposure used on this material.
  36419. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36420. * This corresponds to a photographic exposure.
  36421. */
  36422. set: function (value) {
  36423. this._imageProcessingConfiguration.exposure = value;
  36424. },
  36425. enumerable: true,
  36426. configurable: true
  36427. });
  36428. ;
  36429. ;
  36430. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36431. /**
  36432. * Gets The camera contrast used on this material.
  36433. */
  36434. get: function () {
  36435. return this._imageProcessingConfiguration.contrast;
  36436. },
  36437. /**
  36438. * Sets The camera contrast used on this material.
  36439. */
  36440. set: function (value) {
  36441. this._imageProcessingConfiguration.contrast = value;
  36442. },
  36443. enumerable: true,
  36444. configurable: true
  36445. });
  36446. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36447. /**
  36448. * Gets the Color Grading 2D Lookup Texture.
  36449. */
  36450. get: function () {
  36451. return this._imageProcessingConfiguration.colorGradingTexture;
  36452. },
  36453. /**
  36454. * Sets the Color Grading 2D Lookup Texture.
  36455. */
  36456. set: function (value) {
  36457. this._imageProcessingConfiguration.colorGradingTexture = value;
  36458. },
  36459. enumerable: true,
  36460. configurable: true
  36461. });
  36462. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36463. /**
  36464. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36465. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36466. * 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;
  36467. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36468. */
  36469. get: function () {
  36470. return this._imageProcessingConfiguration.colorCurves;
  36471. },
  36472. /**
  36473. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36474. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36475. * 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;
  36476. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36477. */
  36478. set: function (value) {
  36479. this._imageProcessingConfiguration.colorCurves = value;
  36480. },
  36481. enumerable: true,
  36482. configurable: true
  36483. });
  36484. StandardMaterial.prototype.getClassName = function () {
  36485. return "StandardMaterial";
  36486. };
  36487. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36488. get: function () {
  36489. return this._useLogarithmicDepth;
  36490. },
  36491. set: function (value) {
  36492. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36493. this._markAllSubMeshesAsMiscDirty();
  36494. },
  36495. enumerable: true,
  36496. configurable: true
  36497. });
  36498. StandardMaterial.prototype.needAlphaBlending = function () {
  36499. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36500. };
  36501. StandardMaterial.prototype.needAlphaTesting = function () {
  36502. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36503. };
  36504. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36505. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36506. };
  36507. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36508. return this._diffuseTexture;
  36509. };
  36510. /**
  36511. * Child classes can use it to update shaders
  36512. */
  36513. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36514. if (useInstances === void 0) { useInstances = false; }
  36515. if (subMesh.effect && this.isFrozen) {
  36516. if (this._wasPreviouslyReady && subMesh.effect) {
  36517. return true;
  36518. }
  36519. }
  36520. if (!subMesh._materialDefines) {
  36521. subMesh._materialDefines = new StandardMaterialDefines();
  36522. }
  36523. var scene = this.getScene();
  36524. var defines = subMesh._materialDefines;
  36525. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36526. if (defines._renderId === scene.getRenderId()) {
  36527. return true;
  36528. }
  36529. }
  36530. var engine = scene.getEngine();
  36531. // Lights
  36532. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36533. // Textures
  36534. if (defines._areTexturesDirty) {
  36535. defines._needUVs = false;
  36536. defines.MAINUV1 = false;
  36537. defines.MAINUV2 = false;
  36538. if (scene.texturesEnabled) {
  36539. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36540. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36541. return false;
  36542. }
  36543. else {
  36544. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36545. }
  36546. }
  36547. else {
  36548. defines.DIFFUSE = false;
  36549. }
  36550. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36551. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36552. return false;
  36553. }
  36554. else {
  36555. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36556. }
  36557. }
  36558. else {
  36559. defines.AMBIENT = false;
  36560. }
  36561. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36562. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36563. return false;
  36564. }
  36565. else {
  36566. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36567. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36568. }
  36569. }
  36570. else {
  36571. defines.OPACITY = false;
  36572. }
  36573. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36574. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36575. return false;
  36576. }
  36577. else {
  36578. defines._needNormals = true;
  36579. defines.REFLECTION = true;
  36580. defines.ROUGHNESS = (this._roughness > 0);
  36581. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36582. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36583. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36584. switch (this._reflectionTexture.coordinatesMode) {
  36585. case BABYLON.Texture.CUBIC_MODE:
  36586. case BABYLON.Texture.INVCUBIC_MODE:
  36587. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36588. break;
  36589. case BABYLON.Texture.EXPLICIT_MODE:
  36590. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36591. break;
  36592. case BABYLON.Texture.PLANAR_MODE:
  36593. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36594. break;
  36595. case BABYLON.Texture.PROJECTION_MODE:
  36596. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36597. break;
  36598. case BABYLON.Texture.SKYBOX_MODE:
  36599. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36600. break;
  36601. case BABYLON.Texture.SPHERICAL_MODE:
  36602. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36603. break;
  36604. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36605. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36606. break;
  36607. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36608. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36609. break;
  36610. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36611. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36612. break;
  36613. }
  36614. }
  36615. }
  36616. else {
  36617. defines.REFLECTION = false;
  36618. }
  36619. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36620. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36621. return false;
  36622. }
  36623. else {
  36624. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36625. }
  36626. }
  36627. else {
  36628. defines.EMISSIVE = false;
  36629. }
  36630. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36631. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36632. return false;
  36633. }
  36634. else {
  36635. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36636. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36637. }
  36638. }
  36639. else {
  36640. defines.LIGHTMAP = false;
  36641. }
  36642. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36643. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36644. return false;
  36645. }
  36646. else {
  36647. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36648. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36649. }
  36650. }
  36651. else {
  36652. defines.SPECULAR = false;
  36653. }
  36654. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36655. // Bump texure can not be not blocking.
  36656. if (!this._bumpTexture.isReady()) {
  36657. return false;
  36658. }
  36659. else {
  36660. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36661. defines.PARALLAX = this._useParallax;
  36662. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36663. }
  36664. }
  36665. else {
  36666. defines.BUMP = false;
  36667. }
  36668. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36669. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36670. return false;
  36671. }
  36672. else {
  36673. defines._needUVs = true;
  36674. defines.REFRACTION = true;
  36675. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36676. }
  36677. }
  36678. else {
  36679. defines.REFRACTION = false;
  36680. }
  36681. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36682. }
  36683. else {
  36684. defines.DIFFUSE = false;
  36685. defines.AMBIENT = false;
  36686. defines.OPACITY = false;
  36687. defines.REFLECTION = false;
  36688. defines.EMISSIVE = false;
  36689. defines.LIGHTMAP = false;
  36690. defines.BUMP = false;
  36691. defines.REFRACTION = false;
  36692. }
  36693. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  36694. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  36695. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  36696. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36697. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36698. }
  36699. if (defines._areImageProcessingDirty) {
  36700. if (!this._imageProcessingConfiguration.isReady()) {
  36701. return false;
  36702. }
  36703. this._imageProcessingConfiguration.prepareDefines(defines);
  36704. }
  36705. if (defines._areFresnelDirty) {
  36706. if (StandardMaterial.FresnelEnabled) {
  36707. // Fresnel
  36708. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  36709. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  36710. this._reflectionFresnelParameters) {
  36711. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  36712. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  36713. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  36714. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  36715. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  36716. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  36717. defines._needNormals = true;
  36718. defines.FRESNEL = true;
  36719. }
  36720. }
  36721. else {
  36722. defines.FRESNEL = false;
  36723. }
  36724. }
  36725. // Misc.
  36726. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36727. // Attribs
  36728. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  36729. // Values that need to be evaluated on every frame
  36730. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  36731. // Get correct effect
  36732. if (defines.isDirty) {
  36733. defines.markAsProcessed();
  36734. scene.resetCachedMaterial();
  36735. // Fallbacks
  36736. var fallbacks = new BABYLON.EffectFallbacks();
  36737. if (defines.REFLECTION) {
  36738. fallbacks.addFallback(0, "REFLECTION");
  36739. }
  36740. if (defines.SPECULAR) {
  36741. fallbacks.addFallback(0, "SPECULAR");
  36742. }
  36743. if (defines.BUMP) {
  36744. fallbacks.addFallback(0, "BUMP");
  36745. }
  36746. if (defines.PARALLAX) {
  36747. fallbacks.addFallback(1, "PARALLAX");
  36748. }
  36749. if (defines.PARALLAXOCCLUSION) {
  36750. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  36751. }
  36752. if (defines.SPECULAROVERALPHA) {
  36753. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  36754. }
  36755. if (defines.FOG) {
  36756. fallbacks.addFallback(1, "FOG");
  36757. }
  36758. if (defines.POINTSIZE) {
  36759. fallbacks.addFallback(0, "POINTSIZE");
  36760. }
  36761. if (defines.LOGARITHMICDEPTH) {
  36762. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  36763. }
  36764. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  36765. if (defines.SPECULARTERM) {
  36766. fallbacks.addFallback(0, "SPECULARTERM");
  36767. }
  36768. if (defines.DIFFUSEFRESNEL) {
  36769. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  36770. }
  36771. if (defines.OPACITYFRESNEL) {
  36772. fallbacks.addFallback(2, "OPACITYFRESNEL");
  36773. }
  36774. if (defines.REFLECTIONFRESNEL) {
  36775. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  36776. }
  36777. if (defines.EMISSIVEFRESNEL) {
  36778. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  36779. }
  36780. if (defines.FRESNEL) {
  36781. fallbacks.addFallback(4, "FRESNEL");
  36782. }
  36783. //Attributes
  36784. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36785. if (defines.NORMAL) {
  36786. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36787. }
  36788. if (defines.UV1) {
  36789. attribs.push(BABYLON.VertexBuffer.UVKind);
  36790. }
  36791. if (defines.UV2) {
  36792. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36793. }
  36794. if (defines.VERTEXCOLOR) {
  36795. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36796. }
  36797. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36798. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36799. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36800. var shaderName = "default";
  36801. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  36802. "vFogInfos", "vFogColor", "pointSize",
  36803. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36804. "mBones",
  36805. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36806. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  36807. "logarithmicDepthConstant", "vTangentSpaceParams"
  36808. ];
  36809. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  36810. var uniformBuffers = ["Material", "Scene"];
  36811. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36812. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36813. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36814. uniformsNames: uniforms,
  36815. uniformBuffersNames: uniformBuffers,
  36816. samplers: samplers,
  36817. defines: defines,
  36818. maxSimultaneousLights: this._maxSimultaneousLights
  36819. });
  36820. if (this.customShaderNameResolve) {
  36821. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  36822. }
  36823. var join = defines.toString();
  36824. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  36825. attributes: attribs,
  36826. uniformsNames: uniforms,
  36827. uniformBuffersNames: uniformBuffers,
  36828. samplers: samplers,
  36829. defines: join,
  36830. fallbacks: fallbacks,
  36831. onCompiled: this.onCompiled,
  36832. onError: this.onError,
  36833. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36834. }, engine), defines);
  36835. this.buildUniformLayout();
  36836. }
  36837. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36838. return false;
  36839. }
  36840. defines._renderId = scene.getRenderId();
  36841. this._wasPreviouslyReady = true;
  36842. return true;
  36843. };
  36844. StandardMaterial.prototype.buildUniformLayout = function () {
  36845. // Order is important !
  36846. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  36847. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  36848. this._uniformBuffer.addUniform("opacityParts", 4);
  36849. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  36850. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  36851. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  36852. this._uniformBuffer.addUniform("refractionRightColor", 4);
  36853. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  36854. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  36855. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  36856. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  36857. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36858. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36859. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36860. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36861. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  36862. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36863. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  36864. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36865. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36866. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36867. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36868. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36869. this._uniformBuffer.addUniform("specularMatrix", 16);
  36870. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36871. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36872. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36873. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36874. this._uniformBuffer.addUniform("vSpecularColor", 4);
  36875. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36876. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  36877. this._uniformBuffer.addUniform("pointSize", 1);
  36878. this._uniformBuffer.create();
  36879. };
  36880. StandardMaterial.prototype.unbind = function () {
  36881. if (this._activeEffect) {
  36882. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36883. this._activeEffect.setTexture("reflection2DSampler", null);
  36884. }
  36885. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36886. this._activeEffect.setTexture("refraction2DSampler", null);
  36887. }
  36888. }
  36889. _super.prototype.unbind.call(this);
  36890. };
  36891. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36892. var scene = this.getScene();
  36893. var defines = subMesh._materialDefines;
  36894. if (!defines) {
  36895. return;
  36896. }
  36897. var effect = subMesh.effect;
  36898. if (!effect) {
  36899. return;
  36900. }
  36901. this._activeEffect = effect;
  36902. // Matrices
  36903. this.bindOnlyWorldMatrix(world);
  36904. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36905. // Bones
  36906. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  36907. if (mustRebind) {
  36908. this._uniformBuffer.bindToEffect(effect, "Material");
  36909. this.bindViewProjection(effect);
  36910. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36911. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  36912. // Fresnel
  36913. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  36914. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  36915. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  36916. }
  36917. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  36918. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  36919. }
  36920. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  36921. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  36922. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  36923. }
  36924. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  36925. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  36926. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  36927. }
  36928. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  36929. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  36930. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  36931. }
  36932. }
  36933. // Textures
  36934. if (scene.texturesEnabled) {
  36935. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36936. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  36937. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  36938. }
  36939. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36940. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  36941. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  36942. }
  36943. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36944. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  36945. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  36946. }
  36947. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36948. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  36949. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  36950. }
  36951. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36952. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  36953. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  36954. }
  36955. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36956. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  36957. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  36958. }
  36959. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36960. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  36961. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  36962. }
  36963. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  36964. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  36965. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  36966. if (scene._mirroredCameraPosition) {
  36967. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  36968. }
  36969. else {
  36970. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  36971. }
  36972. }
  36973. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36974. var depth = 1.0;
  36975. if (!this._refractionTexture.isCube) {
  36976. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  36977. if (this._refractionTexture.depth) {
  36978. depth = this._refractionTexture.depth;
  36979. }
  36980. }
  36981. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  36982. }
  36983. }
  36984. // Point size
  36985. if (this.pointsCloud) {
  36986. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  36987. }
  36988. if (defines.SPECULARTERM) {
  36989. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  36990. }
  36991. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  36992. // Diffuse
  36993. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  36994. }
  36995. // Textures
  36996. if (scene.texturesEnabled) {
  36997. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36998. effect.setTexture("diffuseSampler", this._diffuseTexture);
  36999. }
  37000. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37001. effect.setTexture("ambientSampler", this._ambientTexture);
  37002. }
  37003. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37004. effect.setTexture("opacitySampler", this._opacityTexture);
  37005. }
  37006. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37007. if (this._reflectionTexture.isCube) {
  37008. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37009. }
  37010. else {
  37011. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37012. }
  37013. }
  37014. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37015. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37016. }
  37017. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37018. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37019. }
  37020. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37021. effect.setTexture("specularSampler", this._specularTexture);
  37022. }
  37023. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37024. effect.setTexture("bumpSampler", this._bumpTexture);
  37025. }
  37026. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37027. var depth = 1.0;
  37028. if (this._refractionTexture.isCube) {
  37029. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37030. }
  37031. else {
  37032. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37033. }
  37034. }
  37035. }
  37036. // Clip plane
  37037. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37038. // Colors
  37039. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37040. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37041. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37042. }
  37043. if (mustRebind || !this.isFrozen) {
  37044. // Lights
  37045. if (scene.lightsEnabled && !this._disableLighting) {
  37046. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37047. }
  37048. // View
  37049. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37050. this.bindView(effect);
  37051. }
  37052. // Fog
  37053. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37054. // Morph targets
  37055. if (defines.NUM_MORPH_INFLUENCERS) {
  37056. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37057. }
  37058. // Log. depth
  37059. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37060. // image processing
  37061. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37062. this._imageProcessingConfiguration.bind(this._activeEffect);
  37063. }
  37064. }
  37065. this._uniformBuffer.update();
  37066. this._afterBind(mesh, this._activeEffect);
  37067. };
  37068. StandardMaterial.prototype.getAnimatables = function () {
  37069. var results = [];
  37070. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37071. results.push(this._diffuseTexture);
  37072. }
  37073. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37074. results.push(this._ambientTexture);
  37075. }
  37076. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37077. results.push(this._opacityTexture);
  37078. }
  37079. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37080. results.push(this._reflectionTexture);
  37081. }
  37082. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37083. results.push(this._emissiveTexture);
  37084. }
  37085. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37086. results.push(this._specularTexture);
  37087. }
  37088. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37089. results.push(this._bumpTexture);
  37090. }
  37091. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37092. results.push(this._lightmapTexture);
  37093. }
  37094. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37095. results.push(this._refractionTexture);
  37096. }
  37097. return results;
  37098. };
  37099. StandardMaterial.prototype.getActiveTextures = function () {
  37100. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37101. if (this._diffuseTexture) {
  37102. activeTextures.push(this._diffuseTexture);
  37103. }
  37104. if (this._ambientTexture) {
  37105. activeTextures.push(this._ambientTexture);
  37106. }
  37107. if (this._opacityTexture) {
  37108. activeTextures.push(this._opacityTexture);
  37109. }
  37110. if (this._reflectionTexture) {
  37111. activeTextures.push(this._reflectionTexture);
  37112. }
  37113. if (this._emissiveTexture) {
  37114. activeTextures.push(this._emissiveTexture);
  37115. }
  37116. if (this._specularTexture) {
  37117. activeTextures.push(this._specularTexture);
  37118. }
  37119. if (this._bumpTexture) {
  37120. activeTextures.push(this._bumpTexture);
  37121. }
  37122. if (this._lightmapTexture) {
  37123. activeTextures.push(this._lightmapTexture);
  37124. }
  37125. if (this._refractionTexture) {
  37126. activeTextures.push(this._refractionTexture);
  37127. }
  37128. return activeTextures;
  37129. };
  37130. StandardMaterial.prototype.hasTexture = function (texture) {
  37131. if (_super.prototype.hasTexture.call(this, texture)) {
  37132. return true;
  37133. }
  37134. if (this._diffuseTexture === texture) {
  37135. return true;
  37136. }
  37137. if (this._ambientTexture === texture) {
  37138. return true;
  37139. }
  37140. if (this._opacityTexture === texture) {
  37141. return true;
  37142. }
  37143. if (this._reflectionTexture === texture) {
  37144. return true;
  37145. }
  37146. if (this._emissiveTexture === texture) {
  37147. return true;
  37148. }
  37149. if (this._specularTexture === texture) {
  37150. return true;
  37151. }
  37152. if (this._bumpTexture === texture) {
  37153. return true;
  37154. }
  37155. if (this._lightmapTexture === texture) {
  37156. return true;
  37157. }
  37158. if (this._refractionTexture === texture) {
  37159. return true;
  37160. }
  37161. return false;
  37162. };
  37163. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37164. if (forceDisposeTextures) {
  37165. if (this._diffuseTexture) {
  37166. this._diffuseTexture.dispose();
  37167. }
  37168. if (this._ambientTexture) {
  37169. this._ambientTexture.dispose();
  37170. }
  37171. if (this._opacityTexture) {
  37172. this._opacityTexture.dispose();
  37173. }
  37174. if (this._reflectionTexture) {
  37175. this._reflectionTexture.dispose();
  37176. }
  37177. if (this._emissiveTexture) {
  37178. this._emissiveTexture.dispose();
  37179. }
  37180. if (this._specularTexture) {
  37181. this._specularTexture.dispose();
  37182. }
  37183. if (this._bumpTexture) {
  37184. this._bumpTexture.dispose();
  37185. }
  37186. if (this._lightmapTexture) {
  37187. this._lightmapTexture.dispose();
  37188. }
  37189. if (this._refractionTexture) {
  37190. this._refractionTexture.dispose();
  37191. }
  37192. }
  37193. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37194. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37195. }
  37196. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37197. };
  37198. StandardMaterial.prototype.clone = function (name) {
  37199. var _this = this;
  37200. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37201. result.name = name;
  37202. result.id = name;
  37203. return result;
  37204. };
  37205. StandardMaterial.prototype.serialize = function () {
  37206. return BABYLON.SerializationHelper.Serialize(this);
  37207. };
  37208. // Statics
  37209. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37210. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37211. };
  37212. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37213. get: function () {
  37214. return StandardMaterial._DiffuseTextureEnabled;
  37215. },
  37216. set: function (value) {
  37217. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37218. return;
  37219. }
  37220. StandardMaterial._DiffuseTextureEnabled = value;
  37221. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37222. },
  37223. enumerable: true,
  37224. configurable: true
  37225. });
  37226. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37227. get: function () {
  37228. return StandardMaterial._AmbientTextureEnabled;
  37229. },
  37230. set: function (value) {
  37231. if (StandardMaterial._AmbientTextureEnabled === value) {
  37232. return;
  37233. }
  37234. StandardMaterial._AmbientTextureEnabled = value;
  37235. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37236. },
  37237. enumerable: true,
  37238. configurable: true
  37239. });
  37240. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37241. get: function () {
  37242. return StandardMaterial._OpacityTextureEnabled;
  37243. },
  37244. set: function (value) {
  37245. if (StandardMaterial._OpacityTextureEnabled === value) {
  37246. return;
  37247. }
  37248. StandardMaterial._OpacityTextureEnabled = value;
  37249. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37250. },
  37251. enumerable: true,
  37252. configurable: true
  37253. });
  37254. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37255. get: function () {
  37256. return StandardMaterial._ReflectionTextureEnabled;
  37257. },
  37258. set: function (value) {
  37259. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37260. return;
  37261. }
  37262. StandardMaterial._ReflectionTextureEnabled = value;
  37263. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37264. },
  37265. enumerable: true,
  37266. configurable: true
  37267. });
  37268. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37269. get: function () {
  37270. return StandardMaterial._EmissiveTextureEnabled;
  37271. },
  37272. set: function (value) {
  37273. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37274. return;
  37275. }
  37276. StandardMaterial._EmissiveTextureEnabled = value;
  37277. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37278. },
  37279. enumerable: true,
  37280. configurable: true
  37281. });
  37282. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37283. get: function () {
  37284. return StandardMaterial._SpecularTextureEnabled;
  37285. },
  37286. set: function (value) {
  37287. if (StandardMaterial._SpecularTextureEnabled === value) {
  37288. return;
  37289. }
  37290. StandardMaterial._SpecularTextureEnabled = value;
  37291. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37292. },
  37293. enumerable: true,
  37294. configurable: true
  37295. });
  37296. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37297. get: function () {
  37298. return StandardMaterial._BumpTextureEnabled;
  37299. },
  37300. set: function (value) {
  37301. if (StandardMaterial._BumpTextureEnabled === value) {
  37302. return;
  37303. }
  37304. StandardMaterial._BumpTextureEnabled = value;
  37305. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37306. },
  37307. enumerable: true,
  37308. configurable: true
  37309. });
  37310. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37311. get: function () {
  37312. return StandardMaterial._LightmapTextureEnabled;
  37313. },
  37314. set: function (value) {
  37315. if (StandardMaterial._LightmapTextureEnabled === value) {
  37316. return;
  37317. }
  37318. StandardMaterial._LightmapTextureEnabled = value;
  37319. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37320. },
  37321. enumerable: true,
  37322. configurable: true
  37323. });
  37324. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37325. get: function () {
  37326. return StandardMaterial._RefractionTextureEnabled;
  37327. },
  37328. set: function (value) {
  37329. if (StandardMaterial._RefractionTextureEnabled === value) {
  37330. return;
  37331. }
  37332. StandardMaterial._RefractionTextureEnabled = value;
  37333. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37334. },
  37335. enumerable: true,
  37336. configurable: true
  37337. });
  37338. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37339. get: function () {
  37340. return StandardMaterial._ColorGradingTextureEnabled;
  37341. },
  37342. set: function (value) {
  37343. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37344. return;
  37345. }
  37346. StandardMaterial._ColorGradingTextureEnabled = value;
  37347. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37348. },
  37349. enumerable: true,
  37350. configurable: true
  37351. });
  37352. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37353. get: function () {
  37354. return StandardMaterial._FresnelEnabled;
  37355. },
  37356. set: function (value) {
  37357. if (StandardMaterial._FresnelEnabled === value) {
  37358. return;
  37359. }
  37360. StandardMaterial._FresnelEnabled = value;
  37361. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37362. },
  37363. enumerable: true,
  37364. configurable: true
  37365. });
  37366. // Flags used to enable or disable a type of texture for all Standard Materials
  37367. StandardMaterial._DiffuseTextureEnabled = true;
  37368. StandardMaterial._AmbientTextureEnabled = true;
  37369. StandardMaterial._OpacityTextureEnabled = true;
  37370. StandardMaterial._ReflectionTextureEnabled = true;
  37371. StandardMaterial._EmissiveTextureEnabled = true;
  37372. StandardMaterial._SpecularTextureEnabled = true;
  37373. StandardMaterial._BumpTextureEnabled = true;
  37374. StandardMaterial._LightmapTextureEnabled = true;
  37375. StandardMaterial._RefractionTextureEnabled = true;
  37376. StandardMaterial._ColorGradingTextureEnabled = true;
  37377. StandardMaterial._FresnelEnabled = true;
  37378. __decorate([
  37379. BABYLON.serializeAsTexture("diffuseTexture")
  37380. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37381. __decorate([
  37382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37383. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37384. __decorate([
  37385. BABYLON.serializeAsTexture("ambientTexture")
  37386. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37387. __decorate([
  37388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37389. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37390. __decorate([
  37391. BABYLON.serializeAsTexture("opacityTexture")
  37392. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37393. __decorate([
  37394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37395. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37396. __decorate([
  37397. BABYLON.serializeAsTexture("reflectionTexture")
  37398. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37399. __decorate([
  37400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37401. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37402. __decorate([
  37403. BABYLON.serializeAsTexture("emissiveTexture")
  37404. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37405. __decorate([
  37406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37407. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37408. __decorate([
  37409. BABYLON.serializeAsTexture("specularTexture")
  37410. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37411. __decorate([
  37412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37413. ], StandardMaterial.prototype, "specularTexture", void 0);
  37414. __decorate([
  37415. BABYLON.serializeAsTexture("bumpTexture")
  37416. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37417. __decorate([
  37418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37419. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37420. __decorate([
  37421. BABYLON.serializeAsTexture("lightmapTexture")
  37422. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37423. __decorate([
  37424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37425. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37426. __decorate([
  37427. BABYLON.serializeAsTexture("refractionTexture")
  37428. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37429. __decorate([
  37430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37431. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37432. __decorate([
  37433. BABYLON.serializeAsColor3("ambient")
  37434. ], StandardMaterial.prototype, "ambientColor", void 0);
  37435. __decorate([
  37436. BABYLON.serializeAsColor3("diffuse")
  37437. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37438. __decorate([
  37439. BABYLON.serializeAsColor3("specular")
  37440. ], StandardMaterial.prototype, "specularColor", void 0);
  37441. __decorate([
  37442. BABYLON.serializeAsColor3("emissive")
  37443. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37444. __decorate([
  37445. BABYLON.serialize()
  37446. ], StandardMaterial.prototype, "specularPower", void 0);
  37447. __decorate([
  37448. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37449. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37450. __decorate([
  37451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37452. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37453. __decorate([
  37454. BABYLON.serialize("useEmissiveAsIllumination")
  37455. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37456. __decorate([
  37457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37458. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37459. __decorate([
  37460. BABYLON.serialize("linkEmissiveWithDiffuse")
  37461. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37462. __decorate([
  37463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37464. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37465. __decorate([
  37466. BABYLON.serialize("useSpecularOverAlpha")
  37467. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37468. __decorate([
  37469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37470. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37471. __decorate([
  37472. BABYLON.serialize("useReflectionOverAlpha")
  37473. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37474. __decorate([
  37475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37476. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37477. __decorate([
  37478. BABYLON.serialize("disableLighting")
  37479. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37480. __decorate([
  37481. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37482. ], StandardMaterial.prototype, "disableLighting", void 0);
  37483. __decorate([
  37484. BABYLON.serialize("useParallax")
  37485. ], StandardMaterial.prototype, "_useParallax", void 0);
  37486. __decorate([
  37487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37488. ], StandardMaterial.prototype, "useParallax", void 0);
  37489. __decorate([
  37490. BABYLON.serialize("useParallaxOcclusion")
  37491. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37492. __decorate([
  37493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37494. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37495. __decorate([
  37496. BABYLON.serialize()
  37497. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37498. __decorate([
  37499. BABYLON.serialize("roughness")
  37500. ], StandardMaterial.prototype, "_roughness", void 0);
  37501. __decorate([
  37502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37503. ], StandardMaterial.prototype, "roughness", void 0);
  37504. __decorate([
  37505. BABYLON.serialize()
  37506. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37507. __decorate([
  37508. BABYLON.serialize()
  37509. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37510. __decorate([
  37511. BABYLON.serialize("useLightmapAsShadowmap")
  37512. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37513. __decorate([
  37514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37515. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37516. __decorate([
  37517. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37518. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37519. __decorate([
  37520. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37521. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37522. __decorate([
  37523. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37524. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37525. __decorate([
  37526. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37527. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37528. __decorate([
  37529. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37530. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37531. __decorate([
  37532. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37533. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37534. __decorate([
  37535. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37536. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37537. __decorate([
  37538. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37539. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37540. __decorate([
  37541. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37542. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37543. __decorate([
  37544. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37545. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37546. __decorate([
  37547. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37548. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37549. __decorate([
  37550. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37551. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37552. __decorate([
  37553. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37554. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37555. __decorate([
  37556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37557. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37558. __decorate([
  37559. BABYLON.serialize("maxSimultaneousLights")
  37560. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37561. __decorate([
  37562. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37563. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37564. __decorate([
  37565. BABYLON.serialize("invertNormalMapX")
  37566. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37567. __decorate([
  37568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37569. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37570. __decorate([
  37571. BABYLON.serialize("invertNormalMapY")
  37572. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37573. __decorate([
  37574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37575. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37576. __decorate([
  37577. BABYLON.serialize("twoSidedLighting")
  37578. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37579. __decorate([
  37580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37581. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37582. __decorate([
  37583. BABYLON.serialize()
  37584. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37585. return StandardMaterial;
  37586. }(BABYLON.PushMaterial));
  37587. BABYLON.StandardMaterial = StandardMaterial;
  37588. })(BABYLON || (BABYLON = {}));
  37589. //# sourceMappingURL=babylon.standardMaterial.js.map
  37590. var BABYLON;
  37591. (function (BABYLON) {
  37592. var PBRMaterialDefines = /** @class */ (function (_super) {
  37593. __extends(PBRMaterialDefines, _super);
  37594. function PBRMaterialDefines() {
  37595. var _this = _super.call(this) || this;
  37596. _this.PBR = true;
  37597. _this.MAINUV1 = false;
  37598. _this.MAINUV2 = false;
  37599. _this.UV1 = false;
  37600. _this.UV2 = false;
  37601. _this.ALBEDO = false;
  37602. _this.ALBEDODIRECTUV = 0;
  37603. _this.VERTEXCOLOR = false;
  37604. _this.AMBIENT = false;
  37605. _this.AMBIENTDIRECTUV = 0;
  37606. _this.AMBIENTINGRAYSCALE = false;
  37607. _this.OPACITY = false;
  37608. _this.VERTEXALPHA = false;
  37609. _this.OPACITYDIRECTUV = 0;
  37610. _this.OPACITYRGB = false;
  37611. _this.ALPHATEST = false;
  37612. _this.DEPTHPREPASS = false;
  37613. _this.ALPHABLEND = false;
  37614. _this.ALPHAFROMALBEDO = false;
  37615. _this.ALPHATESTVALUE = 0.5;
  37616. _this.SPECULAROVERALPHA = false;
  37617. _this.RADIANCEOVERALPHA = false;
  37618. _this.ALPHAFRESNEL = false;
  37619. _this.LINEARALPHAFRESNEL = false;
  37620. _this.PREMULTIPLYALPHA = false;
  37621. _this.EMISSIVE = false;
  37622. _this.EMISSIVEDIRECTUV = 0;
  37623. _this.REFLECTIVITY = false;
  37624. _this.REFLECTIVITYDIRECTUV = 0;
  37625. _this.SPECULARTERM = false;
  37626. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37627. _this.MICROSURFACEAUTOMATIC = false;
  37628. _this.LODBASEDMICROSFURACE = false;
  37629. _this.MICROSURFACEMAP = false;
  37630. _this.MICROSURFACEMAPDIRECTUV = 0;
  37631. _this.METALLICWORKFLOW = false;
  37632. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37633. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37634. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37635. _this.AOSTOREINMETALMAPRED = false;
  37636. _this.ENVIRONMENTBRDF = false;
  37637. _this.NORMAL = false;
  37638. _this.TANGENT = false;
  37639. _this.BUMP = false;
  37640. _this.BUMPDIRECTUV = 0;
  37641. _this.PARALLAX = false;
  37642. _this.PARALLAXOCCLUSION = false;
  37643. _this.NORMALXYSCALE = true;
  37644. _this.LIGHTMAP = false;
  37645. _this.LIGHTMAPDIRECTUV = 0;
  37646. _this.USELIGHTMAPASSHADOWMAP = false;
  37647. _this.REFLECTION = false;
  37648. _this.REFLECTIONMAP_3D = false;
  37649. _this.REFLECTIONMAP_SPHERICAL = false;
  37650. _this.REFLECTIONMAP_PLANAR = false;
  37651. _this.REFLECTIONMAP_CUBIC = false;
  37652. _this.REFLECTIONMAP_PROJECTION = false;
  37653. _this.REFLECTIONMAP_SKYBOX = false;
  37654. _this.REFLECTIONMAP_EXPLICIT = false;
  37655. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37656. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37657. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37658. _this.INVERTCUBICMAP = false;
  37659. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37660. _this.USESPHERICALINVERTEX = false;
  37661. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37662. _this.LODINREFLECTIONALPHA = false;
  37663. _this.GAMMAREFLECTION = false;
  37664. _this.RADIANCEOCCLUSION = false;
  37665. _this.HORIZONOCCLUSION = false;
  37666. _this.REFRACTION = false;
  37667. _this.REFRACTIONMAP_3D = false;
  37668. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37669. _this.LODINREFRACTIONALPHA = false;
  37670. _this.GAMMAREFRACTION = false;
  37671. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37672. _this.INSTANCES = false;
  37673. _this.NUM_BONE_INFLUENCERS = 0;
  37674. _this.BonesPerMesh = 0;
  37675. _this.NONUNIFORMSCALING = false;
  37676. _this.MORPHTARGETS = false;
  37677. _this.MORPHTARGETS_NORMAL = false;
  37678. _this.MORPHTARGETS_TANGENT = false;
  37679. _this.NUM_MORPH_INFLUENCERS = 0;
  37680. _this.IMAGEPROCESSING = false;
  37681. _this.VIGNETTE = false;
  37682. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37683. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37684. _this.TONEMAPPING = false;
  37685. _this.CONTRAST = false;
  37686. _this.COLORCURVES = false;
  37687. _this.COLORGRADING = false;
  37688. _this.COLORGRADING3D = false;
  37689. _this.SAMPLER3DGREENDEPTH = false;
  37690. _this.SAMPLER3DBGRMAP = false;
  37691. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37692. _this.EXPOSURE = false;
  37693. _this.USEPHYSICALLIGHTFALLOFF = false;
  37694. _this.TWOSIDEDLIGHTING = false;
  37695. _this.SHADOWFLOAT = false;
  37696. _this.CLIPPLANE = false;
  37697. _this.POINTSIZE = false;
  37698. _this.FOG = false;
  37699. _this.LOGARITHMICDEPTH = false;
  37700. _this.FORCENORMALFORWARD = false;
  37701. _this.rebuild();
  37702. return _this;
  37703. }
  37704. PBRMaterialDefines.prototype.reset = function () {
  37705. _super.prototype.reset.call(this);
  37706. this.ALPHATESTVALUE = 0.5;
  37707. this.PBR = true;
  37708. };
  37709. return PBRMaterialDefines;
  37710. }(BABYLON.MaterialDefines));
  37711. /**
  37712. * The Physically based material base class of BJS.
  37713. *
  37714. * This offers the main features of a standard PBR material.
  37715. * For more information, please refer to the documentation :
  37716. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37717. */
  37718. var PBRBaseMaterial = /** @class */ (function (_super) {
  37719. __extends(PBRBaseMaterial, _super);
  37720. /**
  37721. * Instantiates a new PBRMaterial instance.
  37722. *
  37723. * @param name The material name
  37724. * @param scene The scene the material will be use in.
  37725. */
  37726. function PBRBaseMaterial(name, scene) {
  37727. var _this = _super.call(this, name, scene) || this;
  37728. /**
  37729. * Intensity of the direct lights e.g. the four lights available in your scene.
  37730. * This impacts both the direct diffuse and specular highlights.
  37731. */
  37732. _this._directIntensity = 1.0;
  37733. /**
  37734. * Intensity of the emissive part of the material.
  37735. * This helps controlling the emissive effect without modifying the emissive color.
  37736. */
  37737. _this._emissiveIntensity = 1.0;
  37738. /**
  37739. * Intensity of the environment e.g. how much the environment will light the object
  37740. * either through harmonics for rough material or through the refelction for shiny ones.
  37741. */
  37742. _this._environmentIntensity = 1.0;
  37743. /**
  37744. * This is a special control allowing the reduction of the specular highlights coming from the
  37745. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37746. */
  37747. _this._specularIntensity = 1.0;
  37748. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37749. /**
  37750. * Debug Control allowing disabling the bump map on this material.
  37751. */
  37752. _this._disableBumpMap = false;
  37753. /**
  37754. * AKA Occlusion Texture Intensity in other nomenclature.
  37755. */
  37756. _this._ambientTextureStrength = 1.0;
  37757. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37758. /**
  37759. * AKA Diffuse Color in other nomenclature.
  37760. */
  37761. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37762. /**
  37763. * AKA Specular Color in other nomenclature.
  37764. */
  37765. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37766. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37767. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37768. /**
  37769. * AKA Glossiness in other nomenclature.
  37770. */
  37771. _this._microSurface = 0.9;
  37772. /**
  37773. * source material index of refraction (IOR)' / 'destination material IOR.
  37774. */
  37775. _this._indexOfRefraction = 0.66;
  37776. /**
  37777. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37778. */
  37779. _this._invertRefractionY = false;
  37780. /**
  37781. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37782. * Materials half opaque for instance using refraction could benefit from this control.
  37783. */
  37784. _this._linkRefractionWithTransparency = false;
  37785. _this._useLightmapAsShadowmap = false;
  37786. /**
  37787. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37788. * makes the reflect vector face the model (under horizon).
  37789. */
  37790. _this._useHorizonOcclusion = true;
  37791. /**
  37792. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37793. * too much the area relying on ambient texture to define their ambient occlusion.
  37794. */
  37795. _this._useRadianceOcclusion = true;
  37796. /**
  37797. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37798. */
  37799. _this._useAlphaFromAlbedoTexture = false;
  37800. /**
  37801. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37802. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37803. */
  37804. _this._useSpecularOverAlpha = true;
  37805. /**
  37806. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37807. */
  37808. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37809. /**
  37810. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37811. */
  37812. _this._useRoughnessFromMetallicTextureAlpha = true;
  37813. /**
  37814. * Specifies if the metallic texture contains the roughness information in its green channel.
  37815. */
  37816. _this._useRoughnessFromMetallicTextureGreen = false;
  37817. /**
  37818. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37819. */
  37820. _this._useMetallnessFromMetallicTextureBlue = false;
  37821. /**
  37822. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37823. */
  37824. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37825. /**
  37826. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37827. */
  37828. _this._useAmbientInGrayScale = false;
  37829. /**
  37830. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37831. * The material will try to infer what glossiness each pixel should be.
  37832. */
  37833. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37834. /**
  37835. * BJS is using an harcoded light falloff based on a manually sets up range.
  37836. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37837. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37838. */
  37839. _this._usePhysicalLightFalloff = true;
  37840. /**
  37841. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37842. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37843. */
  37844. _this._useRadianceOverAlpha = true;
  37845. /**
  37846. * Allows using the bump map in parallax mode.
  37847. */
  37848. _this._useParallax = false;
  37849. /**
  37850. * Allows using the bump map in parallax occlusion mode.
  37851. */
  37852. _this._useParallaxOcclusion = false;
  37853. /**
  37854. * Controls the scale bias of the parallax mode.
  37855. */
  37856. _this._parallaxScaleBias = 0.05;
  37857. /**
  37858. * If sets to true, disables all the lights affecting the material.
  37859. */
  37860. _this._disableLighting = false;
  37861. /**
  37862. * Number of Simultaneous lights allowed on the material.
  37863. */
  37864. _this._maxSimultaneousLights = 4;
  37865. /**
  37866. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37867. */
  37868. _this._invertNormalMapX = false;
  37869. /**
  37870. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37871. */
  37872. _this._invertNormalMapY = false;
  37873. /**
  37874. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37875. */
  37876. _this._twoSidedLighting = false;
  37877. /**
  37878. * Defines the alpha limits in alpha test mode.
  37879. */
  37880. _this._alphaCutOff = 0.4;
  37881. /**
  37882. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37883. */
  37884. _this._forceAlphaTest = false;
  37885. /**
  37886. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37887. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37888. */
  37889. _this._useAlphaFresnel = false;
  37890. /**
  37891. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37892. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37893. */
  37894. _this._useLinearAlphaFresnel = false;
  37895. /**
  37896. * The transparency mode of the material.
  37897. */
  37898. _this._transparencyMode = null;
  37899. /**
  37900. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37901. * from cos thetav and roughness:
  37902. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37903. */
  37904. _this._environmentBRDFTexture = null;
  37905. /**
  37906. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37907. */
  37908. _this._forceIrradianceInFragment = false;
  37909. /**
  37910. * Force normal to face away from face.
  37911. */
  37912. _this._forceNormalForward = false;
  37913. /**
  37914. * Force metallic workflow.
  37915. */
  37916. _this._forceMetallicWorkflow = false;
  37917. _this._renderTargets = new BABYLON.SmartArray(16);
  37918. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37919. // Setup the default processing configuration to the scene.
  37920. _this._attachImageProcessingConfiguration(null);
  37921. _this.getRenderTargetTextures = function () {
  37922. _this._renderTargets.reset();
  37923. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37924. _this._renderTargets.push(_this._reflectionTexture);
  37925. }
  37926. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37927. _this._renderTargets.push(_this._refractionTexture);
  37928. }
  37929. return _this._renderTargets;
  37930. };
  37931. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37932. return _this;
  37933. }
  37934. /**
  37935. * Attaches a new image processing configuration to the PBR Material.
  37936. * @param configuration
  37937. */
  37938. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  37939. var _this = this;
  37940. if (configuration === this._imageProcessingConfiguration) {
  37941. return;
  37942. }
  37943. // Detaches observer.
  37944. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37945. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37946. }
  37947. // Pick the scene configuration if needed.
  37948. if (!configuration) {
  37949. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  37950. }
  37951. else {
  37952. this._imageProcessingConfiguration = configuration;
  37953. }
  37954. // Attaches observer.
  37955. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  37956. _this._markAllSubMeshesAsImageProcessingDirty();
  37957. });
  37958. };
  37959. PBRBaseMaterial.prototype.getClassName = function () {
  37960. return "PBRBaseMaterial";
  37961. };
  37962. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  37963. get: function () {
  37964. return this._useLogarithmicDepth;
  37965. },
  37966. set: function (value) {
  37967. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  37968. },
  37969. enumerable: true,
  37970. configurable: true
  37971. });
  37972. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  37973. /**
  37974. * Gets the current transparency mode.
  37975. */
  37976. get: function () {
  37977. return this._transparencyMode;
  37978. },
  37979. /**
  37980. * Sets the transparency mode of the material.
  37981. */
  37982. set: function (value) {
  37983. if (this._transparencyMode === value) {
  37984. return;
  37985. }
  37986. this._transparencyMode = value;
  37987. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  37988. this._markAllSubMeshesAsTexturesDirty();
  37989. },
  37990. enumerable: true,
  37991. configurable: true
  37992. });
  37993. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  37994. /**
  37995. * Returns true if alpha blending should be disabled.
  37996. */
  37997. get: function () {
  37998. return (this._linkRefractionWithTransparency ||
  37999. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38000. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38001. },
  38002. enumerable: true,
  38003. configurable: true
  38004. });
  38005. /**
  38006. * Specifies whether or not this material should be rendered in alpha blend mode.
  38007. */
  38008. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38009. if (this._disableAlphaBlending) {
  38010. return false;
  38011. }
  38012. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38013. };
  38014. /**
  38015. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38016. */
  38017. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38018. if (this._disableAlphaBlending) {
  38019. return false;
  38020. }
  38021. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38022. };
  38023. /**
  38024. * Specifies whether or not this material should be rendered in alpha test mode.
  38025. */
  38026. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38027. if (this._forceAlphaTest) {
  38028. return true;
  38029. }
  38030. if (this._linkRefractionWithTransparency) {
  38031. return false;
  38032. }
  38033. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38034. };
  38035. /**
  38036. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38037. */
  38038. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38039. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38040. };
  38041. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38042. return this._albedoTexture;
  38043. };
  38044. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38045. var _this = this;
  38046. if (subMesh.effect && this.isFrozen) {
  38047. if (this._wasPreviouslyReady) {
  38048. return true;
  38049. }
  38050. }
  38051. if (!subMesh._materialDefines) {
  38052. subMesh._materialDefines = new PBRMaterialDefines();
  38053. }
  38054. var scene = this.getScene();
  38055. var defines = subMesh._materialDefines;
  38056. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38057. if (defines._renderId === scene.getRenderId()) {
  38058. return true;
  38059. }
  38060. }
  38061. var engine = scene.getEngine();
  38062. // Lights
  38063. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38064. defines._needNormals = true;
  38065. // Textures
  38066. if (defines._areTexturesDirty) {
  38067. defines._needUVs = false;
  38068. if (scene.texturesEnabled) {
  38069. if (scene.getEngine().getCaps().textureLOD) {
  38070. defines.LODBASEDMICROSFURACE = true;
  38071. }
  38072. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38073. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38074. return false;
  38075. }
  38076. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38077. }
  38078. else {
  38079. defines.ALBEDO = false;
  38080. }
  38081. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38082. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38083. return false;
  38084. }
  38085. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38086. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38087. }
  38088. else {
  38089. defines.AMBIENT = false;
  38090. }
  38091. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38092. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38093. return false;
  38094. }
  38095. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38096. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38097. }
  38098. else {
  38099. defines.OPACITY = false;
  38100. }
  38101. var reflectionTexture = this._getReflectionTexture();
  38102. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38103. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38104. return false;
  38105. }
  38106. defines.REFLECTION = true;
  38107. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38108. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38109. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38110. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38111. defines.INVERTCUBICMAP = true;
  38112. }
  38113. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38114. switch (reflectionTexture.coordinatesMode) {
  38115. case BABYLON.Texture.CUBIC_MODE:
  38116. case BABYLON.Texture.INVCUBIC_MODE:
  38117. defines.REFLECTIONMAP_CUBIC = true;
  38118. break;
  38119. case BABYLON.Texture.EXPLICIT_MODE:
  38120. defines.REFLECTIONMAP_EXPLICIT = true;
  38121. break;
  38122. case BABYLON.Texture.PLANAR_MODE:
  38123. defines.REFLECTIONMAP_PLANAR = true;
  38124. break;
  38125. case BABYLON.Texture.PROJECTION_MODE:
  38126. defines.REFLECTIONMAP_PROJECTION = true;
  38127. break;
  38128. case BABYLON.Texture.SKYBOX_MODE:
  38129. defines.REFLECTIONMAP_SKYBOX = true;
  38130. break;
  38131. case BABYLON.Texture.SPHERICAL_MODE:
  38132. defines.REFLECTIONMAP_SPHERICAL = true;
  38133. break;
  38134. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38135. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38136. break;
  38137. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38138. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38139. break;
  38140. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38141. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38142. break;
  38143. }
  38144. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38145. if (reflectionTexture.sphericalPolynomial) {
  38146. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38147. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38148. defines.USESPHERICALINVERTEX = false;
  38149. }
  38150. else {
  38151. defines.USESPHERICALINVERTEX = true;
  38152. }
  38153. }
  38154. }
  38155. }
  38156. else {
  38157. defines.REFLECTION = false;
  38158. defines.REFLECTIONMAP_3D = false;
  38159. defines.REFLECTIONMAP_SPHERICAL = false;
  38160. defines.REFLECTIONMAP_PLANAR = false;
  38161. defines.REFLECTIONMAP_CUBIC = false;
  38162. defines.REFLECTIONMAP_PROJECTION = false;
  38163. defines.REFLECTIONMAP_SKYBOX = false;
  38164. defines.REFLECTIONMAP_EXPLICIT = false;
  38165. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38166. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38167. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38168. defines.INVERTCUBICMAP = false;
  38169. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38170. defines.USESPHERICALINVERTEX = false;
  38171. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38172. defines.LODINREFLECTIONALPHA = false;
  38173. defines.GAMMAREFLECTION = false;
  38174. }
  38175. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38176. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38177. return false;
  38178. }
  38179. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38180. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38181. }
  38182. else {
  38183. defines.LIGHTMAP = false;
  38184. }
  38185. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38186. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38187. return false;
  38188. }
  38189. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38190. }
  38191. else {
  38192. defines.EMISSIVE = false;
  38193. }
  38194. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38195. if (this._metallicTexture) {
  38196. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38197. return false;
  38198. }
  38199. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38200. defines.METALLICWORKFLOW = true;
  38201. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38202. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38203. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38204. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38205. }
  38206. else if (this._reflectivityTexture) {
  38207. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38208. return false;
  38209. }
  38210. defines.METALLICWORKFLOW = false;
  38211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38212. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38213. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38214. }
  38215. else {
  38216. defines.METALLICWORKFLOW = false;
  38217. defines.REFLECTIVITY = false;
  38218. }
  38219. if (this._microSurfaceTexture) {
  38220. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38221. return false;
  38222. }
  38223. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38224. }
  38225. else {
  38226. defines.MICROSURFACEMAP = false;
  38227. }
  38228. }
  38229. else {
  38230. defines.REFLECTIVITY = false;
  38231. defines.MICROSURFACEMAP = false;
  38232. }
  38233. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38234. // Bump texure can not be none blocking.
  38235. if (!this._bumpTexture.isReady()) {
  38236. return false;
  38237. }
  38238. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38239. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38240. defines.PARALLAX = true;
  38241. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38242. }
  38243. else {
  38244. defines.PARALLAX = false;
  38245. }
  38246. }
  38247. else {
  38248. defines.BUMP = false;
  38249. }
  38250. var refractionTexture = this._getRefractionTexture();
  38251. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38252. if (!refractionTexture.isReadyOrNotBlocking()) {
  38253. return false;
  38254. }
  38255. defines.REFRACTION = true;
  38256. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38257. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38258. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38259. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38260. if (this._linkRefractionWithTransparency) {
  38261. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38262. }
  38263. }
  38264. else {
  38265. defines.REFRACTION = false;
  38266. }
  38267. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38268. // This is blocking.
  38269. if (!this._environmentBRDFTexture.isReady()) {
  38270. return false;
  38271. }
  38272. defines.ENVIRONMENTBRDF = true;
  38273. }
  38274. else {
  38275. defines.ENVIRONMENTBRDF = false;
  38276. }
  38277. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38278. defines.ALPHAFROMALBEDO = true;
  38279. }
  38280. else {
  38281. defines.ALPHAFROMALBEDO = false;
  38282. }
  38283. }
  38284. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38285. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38286. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38287. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38288. defines.METALLICWORKFLOW = true;
  38289. }
  38290. else {
  38291. defines.METALLICWORKFLOW = false;
  38292. }
  38293. if (!this.backFaceCulling && this._twoSidedLighting) {
  38294. defines.TWOSIDEDLIGHTING = true;
  38295. }
  38296. else {
  38297. defines.TWOSIDEDLIGHTING = false;
  38298. }
  38299. defines.ALPHATESTVALUE = this._alphaCutOff;
  38300. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38301. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38302. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38303. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38304. }
  38305. if (defines._areImageProcessingDirty) {
  38306. if (!this._imageProcessingConfiguration.isReady()) {
  38307. return false;
  38308. }
  38309. this._imageProcessingConfiguration.prepareDefines(defines);
  38310. }
  38311. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38312. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38313. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38314. // Misc.
  38315. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  38316. // Values that need to be evaluated on every frame
  38317. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  38318. // Attribs
  38319. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38320. var bufferMesh = null;
  38321. if (mesh instanceof BABYLON.InstancedMesh) {
  38322. bufferMesh = mesh.sourceMesh;
  38323. }
  38324. else if (mesh instanceof BABYLON.Mesh) {
  38325. bufferMesh = mesh;
  38326. }
  38327. if (bufferMesh) {
  38328. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38329. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38330. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38331. var normals = normalVertexBuffer.getData();
  38332. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38333. var strideSize = normalVertexBuffer.getStrideSize();
  38334. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38335. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38336. defines.NORMAL = false;
  38337. }
  38338. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38339. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38340. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38341. var tangents = tangentVertexBuffer.getData();
  38342. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38343. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38344. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38345. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38346. defines.TANGENT = false;
  38347. }
  38348. }
  38349. }
  38350. else {
  38351. if (!scene.getEngine().getCaps().standardDerivatives) {
  38352. bufferMesh.createNormals(true);
  38353. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38354. }
  38355. }
  38356. }
  38357. }
  38358. // Get correct effect
  38359. if (defines.isDirty) {
  38360. defines.markAsProcessed();
  38361. scene.resetCachedMaterial();
  38362. // Fallbacks
  38363. var fallbacks = new BABYLON.EffectFallbacks();
  38364. var fallbackRank = 0;
  38365. if (defines.USESPHERICALINVERTEX) {
  38366. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38367. }
  38368. if (defines.FOG) {
  38369. fallbacks.addFallback(fallbackRank, "FOG");
  38370. }
  38371. if (defines.POINTSIZE) {
  38372. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38373. }
  38374. if (defines.LOGARITHMICDEPTH) {
  38375. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38376. }
  38377. if (defines.PARALLAX) {
  38378. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38379. }
  38380. if (defines.PARALLAXOCCLUSION) {
  38381. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38382. }
  38383. if (defines.ENVIRONMENTBRDF) {
  38384. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38385. }
  38386. if (defines.TANGENT) {
  38387. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38388. }
  38389. if (defines.BUMP) {
  38390. fallbacks.addFallback(fallbackRank++, "BUMP");
  38391. }
  38392. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38393. if (defines.SPECULARTERM) {
  38394. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38395. }
  38396. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38397. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38398. }
  38399. if (defines.LIGHTMAP) {
  38400. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38401. }
  38402. if (defines.NORMAL) {
  38403. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38404. }
  38405. if (defines.AMBIENT) {
  38406. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38407. }
  38408. if (defines.EMISSIVE) {
  38409. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38410. }
  38411. if (defines.VERTEXCOLOR) {
  38412. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38413. }
  38414. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38415. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38416. }
  38417. if (defines.MORPHTARGETS) {
  38418. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38419. }
  38420. //Attributes
  38421. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38422. if (defines.NORMAL) {
  38423. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38424. }
  38425. if (defines.TANGENT) {
  38426. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38427. }
  38428. if (defines.UV1) {
  38429. attribs.push(BABYLON.VertexBuffer.UVKind);
  38430. }
  38431. if (defines.UV2) {
  38432. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38433. }
  38434. if (defines.VERTEXCOLOR) {
  38435. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38436. }
  38437. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38438. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38439. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38440. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38441. "vFogInfos", "vFogColor", "pointSize",
  38442. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38443. "mBones",
  38444. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38445. "vLightingIntensity",
  38446. "logarithmicDepthConstant",
  38447. "vSphericalX", "vSphericalY", "vSphericalZ",
  38448. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38449. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38450. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38451. "vTangentSpaceParams"
  38452. ];
  38453. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38454. "bumpSampler", "lightmapSampler", "opacitySampler",
  38455. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38456. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38457. "microSurfaceSampler", "environmentBrdfSampler"];
  38458. var uniformBuffers = ["Material", "Scene"];
  38459. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38460. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38461. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38462. uniformsNames: uniforms,
  38463. uniformBuffersNames: uniformBuffers,
  38464. samplers: samplers,
  38465. defines: defines,
  38466. maxSimultaneousLights: this._maxSimultaneousLights
  38467. });
  38468. var onCompiled = function (effect) {
  38469. if (_this.onCompiled) {
  38470. _this.onCompiled(effect);
  38471. }
  38472. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38473. };
  38474. var join = defines.toString();
  38475. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38476. attributes: attribs,
  38477. uniformsNames: uniforms,
  38478. uniformBuffersNames: uniformBuffers,
  38479. samplers: samplers,
  38480. defines: join,
  38481. fallbacks: fallbacks,
  38482. onCompiled: onCompiled,
  38483. onError: this.onError,
  38484. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38485. }, engine), defines);
  38486. this.buildUniformLayout();
  38487. }
  38488. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38489. return false;
  38490. }
  38491. defines._renderId = scene.getRenderId();
  38492. this._wasPreviouslyReady = true;
  38493. return true;
  38494. };
  38495. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38496. // Order is important !
  38497. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38498. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38499. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38500. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38501. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38502. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38503. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38504. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38505. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38506. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38507. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38508. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38509. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38510. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38511. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38512. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38513. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38514. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38515. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38516. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38517. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38518. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38519. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38520. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38521. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38522. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38523. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38524. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38525. this._uniformBuffer.addUniform("pointSize", 1);
  38526. this._uniformBuffer.create();
  38527. };
  38528. PBRBaseMaterial.prototype.unbind = function () {
  38529. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38530. this._uniformBuffer.setTexture("reflectionSampler", null);
  38531. }
  38532. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38533. this._uniformBuffer.setTexture("refractionSampler", null);
  38534. }
  38535. _super.prototype.unbind.call(this);
  38536. };
  38537. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38538. this._activeEffect.setMatrix("world", world);
  38539. };
  38540. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38541. var scene = this.getScene();
  38542. var defines = subMesh._materialDefines;
  38543. if (!defines) {
  38544. return;
  38545. }
  38546. var effect = subMesh.effect;
  38547. if (!effect) {
  38548. return;
  38549. }
  38550. this._activeEffect = effect;
  38551. // Matrices
  38552. this.bindOnlyWorldMatrix(world);
  38553. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38554. // Bones
  38555. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38556. var reflectionTexture = null;
  38557. if (mustRebind) {
  38558. this._uniformBuffer.bindToEffect(effect, "Material");
  38559. this.bindViewProjection(effect);
  38560. reflectionTexture = this._getReflectionTexture();
  38561. var refractionTexture = this._getRefractionTexture();
  38562. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38563. // Texture uniforms
  38564. if (scene.texturesEnabled) {
  38565. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38566. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38567. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38568. }
  38569. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38570. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38571. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38572. }
  38573. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38574. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38575. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38576. }
  38577. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38578. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38579. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38580. var polynomials = reflectionTexture.sphericalPolynomial;
  38581. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38582. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38583. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38584. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38585. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38586. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38587. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38588. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38589. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38590. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38591. }
  38592. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38593. }
  38594. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38595. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38596. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38597. }
  38598. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38599. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38600. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38601. }
  38602. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38603. if (this._metallicTexture) {
  38604. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38605. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38606. }
  38607. else if (this._reflectivityTexture) {
  38608. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38609. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38610. }
  38611. if (this._microSurfaceTexture) {
  38612. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38613. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38614. }
  38615. }
  38616. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38617. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38618. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38619. if (scene._mirroredCameraPosition) {
  38620. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38621. }
  38622. else {
  38623. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38624. }
  38625. }
  38626. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38627. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38628. var depth = 1.0;
  38629. if (!refractionTexture.isCube) {
  38630. if (refractionTexture.depth) {
  38631. depth = refractionTexture.depth;
  38632. }
  38633. }
  38634. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38635. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38636. }
  38637. }
  38638. // Point size
  38639. if (this.pointsCloud) {
  38640. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38641. }
  38642. // Colors
  38643. if (defines.METALLICWORKFLOW) {
  38644. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38645. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38646. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38647. }
  38648. else {
  38649. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38650. }
  38651. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38652. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38653. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38654. // Misc
  38655. this._lightingInfos.x = this._directIntensity;
  38656. this._lightingInfos.y = this._emissiveIntensity;
  38657. this._lightingInfos.z = this._environmentIntensity;
  38658. this._lightingInfos.w = this._specularIntensity;
  38659. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38660. }
  38661. // Textures
  38662. if (scene.texturesEnabled) {
  38663. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38664. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38665. }
  38666. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38667. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38668. }
  38669. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38670. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38671. }
  38672. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38673. if (defines.LODBASEDMICROSFURACE) {
  38674. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38675. }
  38676. else {
  38677. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38678. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38679. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38680. }
  38681. }
  38682. if (defines.ENVIRONMENTBRDF) {
  38683. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38684. }
  38685. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38686. if (defines.LODBASEDMICROSFURACE) {
  38687. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  38688. }
  38689. else {
  38690. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  38691. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  38692. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  38693. }
  38694. }
  38695. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38696. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  38697. }
  38698. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38699. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  38700. }
  38701. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38702. if (this._metallicTexture) {
  38703. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  38704. }
  38705. else if (this._reflectivityTexture) {
  38706. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  38707. }
  38708. if (this._microSurfaceTexture) {
  38709. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  38710. }
  38711. }
  38712. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38713. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  38714. }
  38715. }
  38716. // Clip plane
  38717. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  38718. // Colors
  38719. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  38720. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38721. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  38722. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  38723. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38724. }
  38725. if (mustRebind || !this.isFrozen) {
  38726. // Lights
  38727. if (scene.lightsEnabled && !this._disableLighting) {
  38728. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  38729. }
  38730. // View
  38731. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  38732. this.bindView(effect);
  38733. }
  38734. // Fog
  38735. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  38736. // Morph targets
  38737. if (defines.NUM_MORPH_INFLUENCERS) {
  38738. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  38739. }
  38740. // image processing
  38741. this._imageProcessingConfiguration.bind(this._activeEffect);
  38742. // Log. depth
  38743. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  38744. }
  38745. this._uniformBuffer.update();
  38746. this._afterBind(mesh);
  38747. };
  38748. PBRBaseMaterial.prototype.getAnimatables = function () {
  38749. var results = [];
  38750. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  38751. results.push(this._albedoTexture);
  38752. }
  38753. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38754. results.push(this._ambientTexture);
  38755. }
  38756. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38757. results.push(this._opacityTexture);
  38758. }
  38759. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38760. results.push(this._reflectionTexture);
  38761. }
  38762. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38763. results.push(this._emissiveTexture);
  38764. }
  38765. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  38766. results.push(this._metallicTexture);
  38767. }
  38768. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  38769. results.push(this._reflectivityTexture);
  38770. }
  38771. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38772. results.push(this._bumpTexture);
  38773. }
  38774. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38775. results.push(this._lightmapTexture);
  38776. }
  38777. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38778. results.push(this._refractionTexture);
  38779. }
  38780. return results;
  38781. };
  38782. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38783. if (this._reflectionTexture) {
  38784. return this._reflectionTexture;
  38785. }
  38786. return this.getScene().environmentTexture;
  38787. };
  38788. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38789. if (this._refractionTexture) {
  38790. return this._refractionTexture;
  38791. }
  38792. if (this._linkRefractionWithTransparency) {
  38793. return this.getScene().environmentTexture;
  38794. }
  38795. return null;
  38796. };
  38797. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38798. if (forceDisposeTextures) {
  38799. if (this._albedoTexture) {
  38800. this._albedoTexture.dispose();
  38801. }
  38802. if (this._ambientTexture) {
  38803. this._ambientTexture.dispose();
  38804. }
  38805. if (this._opacityTexture) {
  38806. this._opacityTexture.dispose();
  38807. }
  38808. if (this._reflectionTexture) {
  38809. this._reflectionTexture.dispose();
  38810. }
  38811. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  38812. this._environmentBRDFTexture.dispose();
  38813. }
  38814. if (this._emissiveTexture) {
  38815. this._emissiveTexture.dispose();
  38816. }
  38817. if (this._metallicTexture) {
  38818. this._metallicTexture.dispose();
  38819. }
  38820. if (this._reflectivityTexture) {
  38821. this._reflectivityTexture.dispose();
  38822. }
  38823. if (this._bumpTexture) {
  38824. this._bumpTexture.dispose();
  38825. }
  38826. if (this._lightmapTexture) {
  38827. this._lightmapTexture.dispose();
  38828. }
  38829. if (this._refractionTexture) {
  38830. this._refractionTexture.dispose();
  38831. }
  38832. }
  38833. this._renderTargets.dispose();
  38834. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38835. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38836. }
  38837. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38838. };
  38839. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38840. __decorate([
  38841. BABYLON.serializeAsImageProcessingConfiguration()
  38842. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38843. __decorate([
  38844. BABYLON.serialize()
  38845. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38846. __decorate([
  38847. BABYLON.serialize()
  38848. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  38849. return PBRBaseMaterial;
  38850. }(BABYLON.PushMaterial));
  38851. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38852. })(BABYLON || (BABYLON = {}));
  38853. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38854. var BABYLON;
  38855. (function (BABYLON) {
  38856. /**
  38857. * The Physically based simple base material of BJS.
  38858. *
  38859. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38860. * It is used as the base class for both the specGloss and metalRough conventions.
  38861. */
  38862. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  38863. __extends(PBRBaseSimpleMaterial, _super);
  38864. /**
  38865. * Instantiates a new PBRMaterial instance.
  38866. *
  38867. * @param name The material name
  38868. * @param scene The scene the material will be use in.
  38869. */
  38870. function PBRBaseSimpleMaterial(name, scene) {
  38871. var _this = _super.call(this, name, scene) || this;
  38872. /**
  38873. * Number of Simultaneous lights allowed on the material.
  38874. */
  38875. _this.maxSimultaneousLights = 4;
  38876. /**
  38877. * If sets to true, disables all the lights affecting the material.
  38878. */
  38879. _this.disableLighting = false;
  38880. /**
  38881. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38882. */
  38883. _this.invertNormalMapX = false;
  38884. /**
  38885. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38886. */
  38887. _this.invertNormalMapY = false;
  38888. /**
  38889. * Emissivie color used to self-illuminate the model.
  38890. */
  38891. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38892. /**
  38893. * Occlusion Channel Strenght.
  38894. */
  38895. _this.occlusionStrength = 1.0;
  38896. _this.useLightmapAsShadowmap = false;
  38897. _this._useAlphaFromAlbedoTexture = true;
  38898. _this._useAmbientInGrayScale = true;
  38899. return _this;
  38900. }
  38901. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38902. /**
  38903. * Gets the current double sided mode.
  38904. */
  38905. get: function () {
  38906. return this._twoSidedLighting;
  38907. },
  38908. /**
  38909. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38910. */
  38911. set: function (value) {
  38912. if (this._twoSidedLighting === value) {
  38913. return;
  38914. }
  38915. this._twoSidedLighting = value;
  38916. this.backFaceCulling = !value;
  38917. this._markAllSubMeshesAsTexturesDirty();
  38918. },
  38919. enumerable: true,
  38920. configurable: true
  38921. });
  38922. /**
  38923. * Return the active textures of the material.
  38924. */
  38925. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38926. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38927. if (this.environmentTexture) {
  38928. activeTextures.push(this.environmentTexture);
  38929. }
  38930. if (this.normalTexture) {
  38931. activeTextures.push(this.normalTexture);
  38932. }
  38933. if (this.emissiveTexture) {
  38934. activeTextures.push(this.emissiveTexture);
  38935. }
  38936. if (this.occlusionTexture) {
  38937. activeTextures.push(this.occlusionTexture);
  38938. }
  38939. if (this.lightmapTexture) {
  38940. activeTextures.push(this.lightmapTexture);
  38941. }
  38942. return activeTextures;
  38943. };
  38944. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  38945. if (_super.prototype.hasTexture.call(this, texture)) {
  38946. return true;
  38947. }
  38948. if (this.lightmapTexture === texture) {
  38949. return true;
  38950. }
  38951. return false;
  38952. };
  38953. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  38954. return "PBRBaseSimpleMaterial";
  38955. };
  38956. __decorate([
  38957. BABYLON.serialize(),
  38958. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38959. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  38960. __decorate([
  38961. BABYLON.serialize(),
  38962. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38963. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  38964. __decorate([
  38965. BABYLON.serializeAsTexture(),
  38966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  38967. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  38968. __decorate([
  38969. BABYLON.serialize(),
  38970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38971. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  38972. __decorate([
  38973. BABYLON.serialize(),
  38974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38975. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  38976. __decorate([
  38977. BABYLON.serializeAsTexture(),
  38978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  38979. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  38980. __decorate([
  38981. BABYLON.serializeAsColor3("emissive"),
  38982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38983. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  38984. __decorate([
  38985. BABYLON.serializeAsTexture(),
  38986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38987. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  38988. __decorate([
  38989. BABYLON.serialize(),
  38990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  38991. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  38992. __decorate([
  38993. BABYLON.serializeAsTexture(),
  38994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  38995. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  38996. __decorate([
  38997. BABYLON.serialize(),
  38998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  38999. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39000. __decorate([
  39001. BABYLON.serialize()
  39002. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39003. __decorate([
  39004. BABYLON.serializeAsTexture(),
  39005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39006. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39007. __decorate([
  39008. BABYLON.serialize(),
  39009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39010. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39011. return PBRBaseSimpleMaterial;
  39012. }(BABYLON.PBRBaseMaterial));
  39013. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39014. })(BABYLON || (BABYLON = {}));
  39015. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39016. var BABYLON;
  39017. (function (BABYLON) {
  39018. /**
  39019. * The Physically based material of BJS.
  39020. *
  39021. * This offers the main features of a standard PBR material.
  39022. * For more information, please refer to the documentation :
  39023. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39024. */
  39025. var PBRMaterial = /** @class */ (function (_super) {
  39026. __extends(PBRMaterial, _super);
  39027. /**
  39028. * Instantiates a new PBRMaterial instance.
  39029. *
  39030. * @param name The material name
  39031. * @param scene The scene the material will be use in.
  39032. */
  39033. function PBRMaterial(name, scene) {
  39034. var _this = _super.call(this, name, scene) || this;
  39035. /**
  39036. * Intensity of the direct lights e.g. the four lights available in your scene.
  39037. * This impacts both the direct diffuse and specular highlights.
  39038. */
  39039. _this.directIntensity = 1.0;
  39040. /**
  39041. * Intensity of the emissive part of the material.
  39042. * This helps controlling the emissive effect without modifying the emissive color.
  39043. */
  39044. _this.emissiveIntensity = 1.0;
  39045. /**
  39046. * Intensity of the environment e.g. how much the environment will light the object
  39047. * either through harmonics for rough material or through the refelction for shiny ones.
  39048. */
  39049. _this.environmentIntensity = 1.0;
  39050. /**
  39051. * This is a special control allowing the reduction of the specular highlights coming from the
  39052. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39053. */
  39054. _this.specularIntensity = 1.0;
  39055. /**
  39056. * Debug Control allowing disabling the bump map on this material.
  39057. */
  39058. _this.disableBumpMap = false;
  39059. /**
  39060. * AKA Occlusion Texture Intensity in other nomenclature.
  39061. */
  39062. _this.ambientTextureStrength = 1.0;
  39063. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39064. /**
  39065. * AKA Diffuse Color in other nomenclature.
  39066. */
  39067. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39068. /**
  39069. * AKA Specular Color in other nomenclature.
  39070. */
  39071. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39072. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39073. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39074. /**
  39075. * AKA Glossiness in other nomenclature.
  39076. */
  39077. _this.microSurface = 1.0;
  39078. /**
  39079. * source material index of refraction (IOR)' / 'destination material IOR.
  39080. */
  39081. _this.indexOfRefraction = 0.66;
  39082. /**
  39083. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39084. */
  39085. _this.invertRefractionY = false;
  39086. /**
  39087. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39088. * Materials half opaque for instance using refraction could benefit from this control.
  39089. */
  39090. _this.linkRefractionWithTransparency = false;
  39091. _this.useLightmapAsShadowmap = false;
  39092. /**
  39093. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39094. */
  39095. _this.useAlphaFromAlbedoTexture = false;
  39096. /**
  39097. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39098. */
  39099. _this.forceAlphaTest = false;
  39100. /**
  39101. * Defines the alpha limits in alpha test mode.
  39102. */
  39103. _this.alphaCutOff = 0.4;
  39104. /**
  39105. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39106. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39107. */
  39108. _this.useSpecularOverAlpha = true;
  39109. /**
  39110. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39111. */
  39112. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39113. /**
  39114. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39115. */
  39116. _this.useRoughnessFromMetallicTextureAlpha = true;
  39117. /**
  39118. * Specifies if the metallic texture contains the roughness information in its green channel.
  39119. */
  39120. _this.useRoughnessFromMetallicTextureGreen = false;
  39121. /**
  39122. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39123. */
  39124. _this.useMetallnessFromMetallicTextureBlue = false;
  39125. /**
  39126. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39127. */
  39128. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39129. /**
  39130. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39131. */
  39132. _this.useAmbientInGrayScale = false;
  39133. /**
  39134. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39135. * The material will try to infer what glossiness each pixel should be.
  39136. */
  39137. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39138. /**
  39139. * BJS is using an harcoded light falloff based on a manually sets up range.
  39140. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39141. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39142. */
  39143. _this.usePhysicalLightFalloff = true;
  39144. /**
  39145. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39146. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39147. */
  39148. _this.useRadianceOverAlpha = true;
  39149. /**
  39150. * Allows using the bump map in parallax mode.
  39151. */
  39152. _this.useParallax = false;
  39153. /**
  39154. * Allows using the bump map in parallax occlusion mode.
  39155. */
  39156. _this.useParallaxOcclusion = false;
  39157. /**
  39158. * Controls the scale bias of the parallax mode.
  39159. */
  39160. _this.parallaxScaleBias = 0.05;
  39161. /**
  39162. * If sets to true, disables all the lights affecting the material.
  39163. */
  39164. _this.disableLighting = false;
  39165. /**
  39166. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39167. */
  39168. _this.forceIrradianceInFragment = false;
  39169. /**
  39170. * Number of Simultaneous lights allowed on the material.
  39171. */
  39172. _this.maxSimultaneousLights = 4;
  39173. /**
  39174. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39175. */
  39176. _this.invertNormalMapX = false;
  39177. /**
  39178. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39179. */
  39180. _this.invertNormalMapY = false;
  39181. /**
  39182. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39183. */
  39184. _this.twoSidedLighting = false;
  39185. /**
  39186. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39187. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39188. */
  39189. _this.useAlphaFresnel = false;
  39190. /**
  39191. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39192. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39193. */
  39194. _this.useLinearAlphaFresnel = false;
  39195. /**
  39196. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39197. * And/Or occlude the blended part.
  39198. */
  39199. _this.environmentBRDFTexture = null;
  39200. /**
  39201. * Force normal to face away from face.
  39202. */
  39203. _this.forceNormalForward = false;
  39204. /**
  39205. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39206. * makes the reflect vector face the model (under horizon).
  39207. */
  39208. _this.useHorizonOcclusion = true;
  39209. /**
  39210. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39211. * too much the area relying on ambient texture to define their ambient occlusion.
  39212. */
  39213. _this.useRadianceOcclusion = true;
  39214. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39215. return _this;
  39216. }
  39217. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39218. /**
  39219. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39220. */
  39221. get: function () {
  39222. return this._PBRMATERIAL_OPAQUE;
  39223. },
  39224. enumerable: true,
  39225. configurable: true
  39226. });
  39227. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39228. /**
  39229. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39230. */
  39231. get: function () {
  39232. return this._PBRMATERIAL_ALPHATEST;
  39233. },
  39234. enumerable: true,
  39235. configurable: true
  39236. });
  39237. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39238. /**
  39239. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39240. */
  39241. get: function () {
  39242. return this._PBRMATERIAL_ALPHABLEND;
  39243. },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39248. /**
  39249. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39250. * They are also discarded below the alpha cutoff threshold to improve performances.
  39251. */
  39252. get: function () {
  39253. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39254. },
  39255. enumerable: true,
  39256. configurable: true
  39257. });
  39258. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39259. /**
  39260. * Gets the image processing configuration used either in this material.
  39261. */
  39262. get: function () {
  39263. return this._imageProcessingConfiguration;
  39264. },
  39265. /**
  39266. * Sets the Default image processing configuration used either in the this material.
  39267. *
  39268. * If sets to null, the scene one is in use.
  39269. */
  39270. set: function (value) {
  39271. this._attachImageProcessingConfiguration(value);
  39272. // Ensure the effect will be rebuilt.
  39273. this._markAllSubMeshesAsTexturesDirty();
  39274. },
  39275. enumerable: true,
  39276. configurable: true
  39277. });
  39278. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39279. /**
  39280. * Gets wether the color curves effect is enabled.
  39281. */
  39282. get: function () {
  39283. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39284. },
  39285. /**
  39286. * Sets wether the color curves effect is enabled.
  39287. */
  39288. set: function (value) {
  39289. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39290. },
  39291. enumerable: true,
  39292. configurable: true
  39293. });
  39294. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39295. /**
  39296. * Gets wether the color grading effect is enabled.
  39297. */
  39298. get: function () {
  39299. return this.imageProcessingConfiguration.colorGradingEnabled;
  39300. },
  39301. /**
  39302. * Gets wether the color grading effect is enabled.
  39303. */
  39304. set: function (value) {
  39305. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39306. },
  39307. enumerable: true,
  39308. configurable: true
  39309. });
  39310. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39311. /**
  39312. * Gets wether tonemapping is enabled or not.
  39313. */
  39314. get: function () {
  39315. return this._imageProcessingConfiguration.toneMappingEnabled;
  39316. },
  39317. /**
  39318. * Sets wether tonemapping is enabled or not
  39319. */
  39320. set: function (value) {
  39321. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39322. },
  39323. enumerable: true,
  39324. configurable: true
  39325. });
  39326. ;
  39327. ;
  39328. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39329. /**
  39330. * The camera exposure used on this material.
  39331. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39332. * This corresponds to a photographic exposure.
  39333. */
  39334. get: function () {
  39335. return this._imageProcessingConfiguration.exposure;
  39336. },
  39337. /**
  39338. * The camera exposure used on this material.
  39339. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39340. * This corresponds to a photographic exposure.
  39341. */
  39342. set: function (value) {
  39343. this._imageProcessingConfiguration.exposure = value;
  39344. },
  39345. enumerable: true,
  39346. configurable: true
  39347. });
  39348. ;
  39349. ;
  39350. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39351. /**
  39352. * Gets The camera contrast used on this material.
  39353. */
  39354. get: function () {
  39355. return this._imageProcessingConfiguration.contrast;
  39356. },
  39357. /**
  39358. * Sets The camera contrast used on this material.
  39359. */
  39360. set: function (value) {
  39361. this._imageProcessingConfiguration.contrast = value;
  39362. },
  39363. enumerable: true,
  39364. configurable: true
  39365. });
  39366. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39367. /**
  39368. * Gets the Color Grading 2D Lookup Texture.
  39369. */
  39370. get: function () {
  39371. return this._imageProcessingConfiguration.colorGradingTexture;
  39372. },
  39373. /**
  39374. * Sets the Color Grading 2D Lookup Texture.
  39375. */
  39376. set: function (value) {
  39377. this._imageProcessingConfiguration.colorGradingTexture = value;
  39378. },
  39379. enumerable: true,
  39380. configurable: true
  39381. });
  39382. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39383. /**
  39384. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39385. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39386. * 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;
  39387. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39388. */
  39389. get: function () {
  39390. return this._imageProcessingConfiguration.colorCurves;
  39391. },
  39392. /**
  39393. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39394. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39395. * 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;
  39396. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39397. */
  39398. set: function (value) {
  39399. this._imageProcessingConfiguration.colorCurves = value;
  39400. },
  39401. enumerable: true,
  39402. configurable: true
  39403. });
  39404. PBRMaterial.prototype.getClassName = function () {
  39405. return "PBRMaterial";
  39406. };
  39407. PBRMaterial.prototype.getActiveTextures = function () {
  39408. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39409. if (this._albedoTexture) {
  39410. activeTextures.push(this._albedoTexture);
  39411. }
  39412. if (this._ambientTexture) {
  39413. activeTextures.push(this._ambientTexture);
  39414. }
  39415. if (this._opacityTexture) {
  39416. activeTextures.push(this._opacityTexture);
  39417. }
  39418. if (this._reflectionTexture) {
  39419. activeTextures.push(this._reflectionTexture);
  39420. }
  39421. if (this._emissiveTexture) {
  39422. activeTextures.push(this._emissiveTexture);
  39423. }
  39424. if (this._reflectivityTexture) {
  39425. activeTextures.push(this._reflectivityTexture);
  39426. }
  39427. if (this._metallicTexture) {
  39428. activeTextures.push(this._metallicTexture);
  39429. }
  39430. if (this._microSurfaceTexture) {
  39431. activeTextures.push(this._microSurfaceTexture);
  39432. }
  39433. if (this._bumpTexture) {
  39434. activeTextures.push(this._bumpTexture);
  39435. }
  39436. if (this._lightmapTexture) {
  39437. activeTextures.push(this._lightmapTexture);
  39438. }
  39439. if (this._refractionTexture) {
  39440. activeTextures.push(this._refractionTexture);
  39441. }
  39442. return activeTextures;
  39443. };
  39444. PBRMaterial.prototype.hasTexture = function (texture) {
  39445. if (_super.prototype.hasTexture.call(this, texture)) {
  39446. return true;
  39447. }
  39448. if (this._albedoTexture === texture) {
  39449. return true;
  39450. }
  39451. if (this._ambientTexture === texture) {
  39452. return true;
  39453. }
  39454. if (this._opacityTexture === texture) {
  39455. return true;
  39456. }
  39457. if (this._reflectionTexture === texture) {
  39458. return true;
  39459. }
  39460. if (this._reflectivityTexture === texture) {
  39461. return true;
  39462. }
  39463. if (this._metallicTexture === texture) {
  39464. return true;
  39465. }
  39466. if (this._microSurfaceTexture === texture) {
  39467. return true;
  39468. }
  39469. if (this._bumpTexture === texture) {
  39470. return true;
  39471. }
  39472. if (this._lightmapTexture === texture) {
  39473. return true;
  39474. }
  39475. if (this._refractionTexture === texture) {
  39476. return true;
  39477. }
  39478. return false;
  39479. };
  39480. PBRMaterial.prototype.clone = function (name) {
  39481. var _this = this;
  39482. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39483. clone.id = name;
  39484. clone.name = name;
  39485. return clone;
  39486. };
  39487. PBRMaterial.prototype.serialize = function () {
  39488. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39489. serializationObject.customType = "BABYLON.PBRMaterial";
  39490. return serializationObject;
  39491. };
  39492. // Statics
  39493. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39494. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39495. };
  39496. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39497. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39498. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39499. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39500. __decorate([
  39501. BABYLON.serialize(),
  39502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39503. ], PBRMaterial.prototype, "directIntensity", void 0);
  39504. __decorate([
  39505. BABYLON.serialize(),
  39506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39507. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39508. __decorate([
  39509. BABYLON.serialize(),
  39510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39511. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39512. __decorate([
  39513. BABYLON.serialize(),
  39514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39515. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39516. __decorate([
  39517. BABYLON.serialize(),
  39518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39519. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39520. __decorate([
  39521. BABYLON.serializeAsTexture(),
  39522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39523. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39524. __decorate([
  39525. BABYLON.serializeAsTexture(),
  39526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39527. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39528. __decorate([
  39529. BABYLON.serialize(),
  39530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39531. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39532. __decorate([
  39533. BABYLON.serializeAsTexture(),
  39534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39535. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39536. __decorate([
  39537. BABYLON.serializeAsTexture(),
  39538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39539. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39540. __decorate([
  39541. BABYLON.serializeAsTexture(),
  39542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39543. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39544. __decorate([
  39545. BABYLON.serializeAsTexture(),
  39546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39547. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39548. __decorate([
  39549. BABYLON.serializeAsTexture(),
  39550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39551. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39552. __decorate([
  39553. BABYLON.serialize(),
  39554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39555. ], PBRMaterial.prototype, "metallic", void 0);
  39556. __decorate([
  39557. BABYLON.serialize(),
  39558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39559. ], PBRMaterial.prototype, "roughness", void 0);
  39560. __decorate([
  39561. BABYLON.serializeAsTexture(),
  39562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39563. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39564. __decorate([
  39565. BABYLON.serializeAsTexture(),
  39566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39567. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39568. __decorate([
  39569. BABYLON.serializeAsTexture(),
  39570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39571. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39572. __decorate([
  39573. BABYLON.serializeAsTexture(),
  39574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39575. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39576. __decorate([
  39577. BABYLON.serializeAsColor3("ambient"),
  39578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39579. ], PBRMaterial.prototype, "ambientColor", void 0);
  39580. __decorate([
  39581. BABYLON.serializeAsColor3("albedo"),
  39582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39583. ], PBRMaterial.prototype, "albedoColor", void 0);
  39584. __decorate([
  39585. BABYLON.serializeAsColor3("reflectivity"),
  39586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39587. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39588. __decorate([
  39589. BABYLON.serializeAsColor3("reflection"),
  39590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39591. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39592. __decorate([
  39593. BABYLON.serializeAsColor3("emissive"),
  39594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39595. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39596. __decorate([
  39597. BABYLON.serialize(),
  39598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39599. ], PBRMaterial.prototype, "microSurface", void 0);
  39600. __decorate([
  39601. BABYLON.serialize(),
  39602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39603. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39604. __decorate([
  39605. BABYLON.serialize(),
  39606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39607. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39608. __decorate([
  39609. BABYLON.serialize(),
  39610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39611. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39612. __decorate([
  39613. BABYLON.serialize(),
  39614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39615. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39616. __decorate([
  39617. BABYLON.serialize(),
  39618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39619. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39620. __decorate([
  39621. BABYLON.serialize(),
  39622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39623. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39624. __decorate([
  39625. BABYLON.serialize(),
  39626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39627. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39628. __decorate([
  39629. BABYLON.serialize(),
  39630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39631. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39632. __decorate([
  39633. BABYLON.serialize(),
  39634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39635. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39636. __decorate([
  39637. BABYLON.serialize(),
  39638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39639. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39640. __decorate([
  39641. BABYLON.serialize(),
  39642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39643. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39644. __decorate([
  39645. BABYLON.serialize(),
  39646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39647. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39648. __decorate([
  39649. BABYLON.serialize(),
  39650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39651. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39652. __decorate([
  39653. BABYLON.serialize(),
  39654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39655. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39656. __decorate([
  39657. BABYLON.serialize(),
  39658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39659. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39660. __decorate([
  39661. BABYLON.serialize(),
  39662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39663. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39664. __decorate([
  39665. BABYLON.serialize(),
  39666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39667. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39668. __decorate([
  39669. BABYLON.serialize(),
  39670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39671. ], PBRMaterial.prototype, "useParallax", void 0);
  39672. __decorate([
  39673. BABYLON.serialize(),
  39674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39675. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39676. __decorate([
  39677. BABYLON.serialize(),
  39678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39679. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39680. __decorate([
  39681. BABYLON.serialize(),
  39682. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39683. ], PBRMaterial.prototype, "disableLighting", void 0);
  39684. __decorate([
  39685. BABYLON.serialize(),
  39686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39687. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  39688. __decorate([
  39689. BABYLON.serialize(),
  39690. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39691. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39692. __decorate([
  39693. BABYLON.serialize(),
  39694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39695. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39696. __decorate([
  39697. BABYLON.serialize(),
  39698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39699. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39700. __decorate([
  39701. BABYLON.serialize(),
  39702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39703. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39704. __decorate([
  39705. BABYLON.serialize(),
  39706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39707. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  39708. __decorate([
  39709. BABYLON.serialize(),
  39710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39711. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  39712. __decorate([
  39713. BABYLON.serializeAsTexture(),
  39714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39715. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  39716. __decorate([
  39717. BABYLON.serialize(),
  39718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39719. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  39720. __decorate([
  39721. BABYLON.serialize(),
  39722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39723. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  39724. __decorate([
  39725. BABYLON.serialize(),
  39726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39727. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  39728. return PBRMaterial;
  39729. }(BABYLON.PBRBaseMaterial));
  39730. BABYLON.PBRMaterial = PBRMaterial;
  39731. })(BABYLON || (BABYLON = {}));
  39732. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39733. var BABYLON;
  39734. (function (BABYLON) {
  39735. /**
  39736. * The PBR material of BJS following the metal roughness convention.
  39737. *
  39738. * This fits to the PBR convention in the GLTF definition:
  39739. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39740. */
  39741. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  39742. __extends(PBRMetallicRoughnessMaterial, _super);
  39743. /**
  39744. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39745. *
  39746. * @param name The material name
  39747. * @param scene The scene the material will be use in.
  39748. */
  39749. function PBRMetallicRoughnessMaterial(name, scene) {
  39750. var _this = _super.call(this, name, scene) || this;
  39751. _this._useRoughnessFromMetallicTextureAlpha = false;
  39752. _this._useRoughnessFromMetallicTextureGreen = true;
  39753. _this._useMetallnessFromMetallicTextureBlue = true;
  39754. _this._forceMetallicWorkflow = true;
  39755. return _this;
  39756. }
  39757. /**
  39758. * Return the currrent class name of the material.
  39759. */
  39760. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39761. return "PBRMetallicRoughnessMaterial";
  39762. };
  39763. /**
  39764. * Return the active textures of the material.
  39765. */
  39766. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39767. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39768. if (this.baseTexture) {
  39769. activeTextures.push(this.baseTexture);
  39770. }
  39771. if (this.metallicRoughnessTexture) {
  39772. activeTextures.push(this.metallicRoughnessTexture);
  39773. }
  39774. return activeTextures;
  39775. };
  39776. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39777. if (_super.prototype.hasTexture.call(this, texture)) {
  39778. return true;
  39779. }
  39780. if (this.baseTexture === texture) {
  39781. return true;
  39782. }
  39783. if (this.metallicRoughnessTexture === texture) {
  39784. return true;
  39785. }
  39786. return false;
  39787. };
  39788. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39789. var _this = this;
  39790. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39791. clone.id = name;
  39792. clone.name = name;
  39793. return clone;
  39794. };
  39795. /**
  39796. * Serialize the material to a parsable JSON object.
  39797. */
  39798. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39799. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39800. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39801. return serializationObject;
  39802. };
  39803. /**
  39804. * Parses a JSON object correponding to the serialize function.
  39805. */
  39806. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39807. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39808. };
  39809. __decorate([
  39810. BABYLON.serializeAsColor3(),
  39811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39812. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39813. __decorate([
  39814. BABYLON.serializeAsTexture(),
  39815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39816. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39817. __decorate([
  39818. BABYLON.serialize(),
  39819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39820. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39821. __decorate([
  39822. BABYLON.serialize(),
  39823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39824. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39825. __decorate([
  39826. BABYLON.serializeAsTexture(),
  39827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39828. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39829. return PBRMetallicRoughnessMaterial;
  39830. }(BABYLON.PBRBaseSimpleMaterial));
  39831. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39832. })(BABYLON || (BABYLON = {}));
  39833. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39834. var BABYLON;
  39835. (function (BABYLON) {
  39836. /**
  39837. * The PBR material of BJS following the specular glossiness convention.
  39838. *
  39839. * This fits to the PBR convention in the GLTF definition:
  39840. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39841. */
  39842. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  39843. __extends(PBRSpecularGlossinessMaterial, _super);
  39844. /**
  39845. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39846. *
  39847. * @param name The material name
  39848. * @param scene The scene the material will be use in.
  39849. */
  39850. function PBRSpecularGlossinessMaterial(name, scene) {
  39851. var _this = _super.call(this, name, scene) || this;
  39852. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39853. return _this;
  39854. }
  39855. /**
  39856. * Return the currrent class name of the material.
  39857. */
  39858. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39859. return "PBRSpecularGlossinessMaterial";
  39860. };
  39861. /**
  39862. * Return the active textures of the material.
  39863. */
  39864. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39865. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39866. if (this.diffuseTexture) {
  39867. activeTextures.push(this.diffuseTexture);
  39868. }
  39869. if (this.specularGlossinessTexture) {
  39870. activeTextures.push(this.specularGlossinessTexture);
  39871. }
  39872. return activeTextures;
  39873. };
  39874. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39875. if (_super.prototype.hasTexture.call(this, texture)) {
  39876. return true;
  39877. }
  39878. if (this.diffuseTexture === texture) {
  39879. return true;
  39880. }
  39881. if (this.specularGlossinessTexture === texture) {
  39882. return true;
  39883. }
  39884. return false;
  39885. };
  39886. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39887. var _this = this;
  39888. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39889. clone.id = name;
  39890. clone.name = name;
  39891. return clone;
  39892. };
  39893. /**
  39894. * Serialize the material to a parsable JSON object.
  39895. */
  39896. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39897. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39898. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39899. return serializationObject;
  39900. };
  39901. /**
  39902. * Parses a JSON object correponding to the serialize function.
  39903. */
  39904. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39905. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39906. };
  39907. __decorate([
  39908. BABYLON.serializeAsColor3("diffuse"),
  39909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39910. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39911. __decorate([
  39912. BABYLON.serializeAsTexture(),
  39913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39914. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39915. __decorate([
  39916. BABYLON.serializeAsColor3("specular"),
  39917. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39918. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39919. __decorate([
  39920. BABYLON.serialize(),
  39921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39922. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39923. __decorate([
  39924. BABYLON.serializeAsTexture(),
  39925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39926. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39927. return PBRSpecularGlossinessMaterial;
  39928. }(BABYLON.PBRBaseSimpleMaterial));
  39929. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39930. })(BABYLON || (BABYLON = {}));
  39931. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  39932. var BABYLON;
  39933. (function (BABYLON) {
  39934. BABYLON.CameraInputTypes = {};
  39935. var CameraInputsManager = /** @class */ (function () {
  39936. function CameraInputsManager(camera) {
  39937. this.attached = {};
  39938. this.camera = camera;
  39939. this.checkInputs = function () { };
  39940. }
  39941. /**
  39942. * Add an input method to a camera.
  39943. * builtin inputs example: camera.inputs.addGamepad();
  39944. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  39945. * @param input camera input method
  39946. */
  39947. CameraInputsManager.prototype.add = function (input) {
  39948. var type = input.getSimpleName();
  39949. if (this.attached[type]) {
  39950. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  39951. return;
  39952. }
  39953. this.attached[type] = input;
  39954. input.camera = this.camera;
  39955. //for checkInputs, we are dynamically creating a function
  39956. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  39957. if (input.checkInputs) {
  39958. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  39959. }
  39960. if (this.attachedElement) {
  39961. input.attachControl(this.attachedElement);
  39962. }
  39963. };
  39964. /**
  39965. * Remove a specific input method from a camera
  39966. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  39967. * @param inputToRemove camera input method
  39968. */
  39969. CameraInputsManager.prototype.remove = function (inputToRemove) {
  39970. for (var cam in this.attached) {
  39971. var input = this.attached[cam];
  39972. if (input === inputToRemove) {
  39973. input.detachControl(this.attachedElement);
  39974. input.camera = null;
  39975. delete this.attached[cam];
  39976. this.rebuildInputCheck();
  39977. }
  39978. }
  39979. };
  39980. CameraInputsManager.prototype.removeByType = function (inputType) {
  39981. for (var cam in this.attached) {
  39982. var input = this.attached[cam];
  39983. if (input.getClassName() === inputType) {
  39984. input.detachControl(this.attachedElement);
  39985. input.camera = null;
  39986. delete this.attached[cam];
  39987. this.rebuildInputCheck();
  39988. }
  39989. }
  39990. };
  39991. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  39992. var current = this.checkInputs;
  39993. return function () {
  39994. current();
  39995. fn();
  39996. };
  39997. };
  39998. CameraInputsManager.prototype.attachInput = function (input) {
  39999. if (this.attachedElement) {
  40000. input.attachControl(this.attachedElement, this.noPreventDefault);
  40001. }
  40002. };
  40003. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40004. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40005. if (this.attachedElement) {
  40006. return;
  40007. }
  40008. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40009. this.attachedElement = element;
  40010. this.noPreventDefault = noPreventDefault;
  40011. for (var cam in this.attached) {
  40012. this.attached[cam].attachControl(element, noPreventDefault);
  40013. }
  40014. };
  40015. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40016. if (disconnect === void 0) { disconnect = false; }
  40017. if (this.attachedElement !== element) {
  40018. return;
  40019. }
  40020. for (var cam in this.attached) {
  40021. this.attached[cam].detachControl(element);
  40022. if (disconnect) {
  40023. this.attached[cam].camera = null;
  40024. }
  40025. }
  40026. this.attachedElement = null;
  40027. };
  40028. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40029. this.checkInputs = function () { };
  40030. for (var cam in this.attached) {
  40031. var input = this.attached[cam];
  40032. if (input.checkInputs) {
  40033. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40034. }
  40035. }
  40036. };
  40037. /**
  40038. * Remove all attached input methods from a camera
  40039. */
  40040. CameraInputsManager.prototype.clear = function () {
  40041. if (this.attachedElement) {
  40042. this.detachElement(this.attachedElement, true);
  40043. }
  40044. this.attached = {};
  40045. this.attachedElement = null;
  40046. this.checkInputs = function () { };
  40047. };
  40048. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40049. var inputs = {};
  40050. for (var cam in this.attached) {
  40051. var input = this.attached[cam];
  40052. var res = BABYLON.SerializationHelper.Serialize(input);
  40053. inputs[input.getClassName()] = res;
  40054. }
  40055. serializedCamera.inputsmgr = inputs;
  40056. };
  40057. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40058. var parsedInputs = parsedCamera.inputsmgr;
  40059. if (parsedInputs) {
  40060. this.clear();
  40061. for (var n in parsedInputs) {
  40062. var construct = BABYLON.CameraInputTypes[n];
  40063. if (construct) {
  40064. var parsedinput = parsedInputs[n];
  40065. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40066. this.add(input);
  40067. }
  40068. }
  40069. }
  40070. else {
  40071. //2016-03-08 this part is for managing backward compatibility
  40072. for (var n in this.attached) {
  40073. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40074. if (construct) {
  40075. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40076. this.remove(this.attached[n]);
  40077. this.add(input);
  40078. }
  40079. }
  40080. }
  40081. };
  40082. return CameraInputsManager;
  40083. }());
  40084. BABYLON.CameraInputsManager = CameraInputsManager;
  40085. })(BABYLON || (BABYLON = {}));
  40086. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40087. var BABYLON;
  40088. (function (BABYLON) {
  40089. var TargetCamera = /** @class */ (function (_super) {
  40090. __extends(TargetCamera, _super);
  40091. function TargetCamera(name, position, scene) {
  40092. var _this = _super.call(this, name, position, scene) || this;
  40093. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40094. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40095. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40096. _this.speed = 2.0;
  40097. _this.noRotationConstraint = false;
  40098. _this.lockedTarget = null;
  40099. _this._currentTarget = BABYLON.Vector3.Zero();
  40100. _this._viewMatrix = BABYLON.Matrix.Zero();
  40101. _this._camMatrix = BABYLON.Matrix.Zero();
  40102. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40103. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40104. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40105. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40106. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40107. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40108. _this._tempMatrix = BABYLON.Matrix.Zero();
  40109. return _this;
  40110. }
  40111. TargetCamera.prototype.getFrontPosition = function (distance) {
  40112. this.getWorldMatrix();
  40113. var direction = this.getTarget().subtract(this.position);
  40114. direction.normalize();
  40115. direction.scaleInPlace(distance);
  40116. return this.globalPosition.add(direction);
  40117. };
  40118. TargetCamera.prototype._getLockedTargetPosition = function () {
  40119. if (!this.lockedTarget) {
  40120. return null;
  40121. }
  40122. if (this.lockedTarget.absolutePosition) {
  40123. this.lockedTarget.computeWorldMatrix();
  40124. }
  40125. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40126. };
  40127. TargetCamera.prototype.storeState = function () {
  40128. this._storedPosition = this.position.clone();
  40129. this._storedRotation = this.rotation.clone();
  40130. if (this.rotationQuaternion) {
  40131. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40132. }
  40133. return _super.prototype.storeState.call(this);
  40134. };
  40135. /**
  40136. * Restored camera state. You must call storeState() first
  40137. */
  40138. TargetCamera.prototype._restoreStateValues = function () {
  40139. if (!_super.prototype._restoreStateValues.call(this)) {
  40140. return false;
  40141. }
  40142. this.position = this._storedPosition.clone();
  40143. this.rotation = this._storedRotation.clone();
  40144. if (this.rotationQuaternion) {
  40145. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40146. }
  40147. this.cameraDirection.copyFromFloats(0, 0, 0);
  40148. this.cameraRotation.copyFromFloats(0, 0);
  40149. return true;
  40150. };
  40151. // Cache
  40152. TargetCamera.prototype._initCache = function () {
  40153. _super.prototype._initCache.call(this);
  40154. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40155. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40156. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40157. };
  40158. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40159. if (!ignoreParentClass) {
  40160. _super.prototype._updateCache.call(this);
  40161. }
  40162. var lockedTargetPosition = this._getLockedTargetPosition();
  40163. if (!lockedTargetPosition) {
  40164. this._cache.lockedTarget = null;
  40165. }
  40166. else {
  40167. if (!this._cache.lockedTarget) {
  40168. this._cache.lockedTarget = lockedTargetPosition.clone();
  40169. }
  40170. else {
  40171. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40172. }
  40173. }
  40174. this._cache.rotation.copyFrom(this.rotation);
  40175. if (this.rotationQuaternion)
  40176. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40177. };
  40178. // Synchronized
  40179. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40180. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40181. return false;
  40182. }
  40183. var lockedTargetPosition = this._getLockedTargetPosition();
  40184. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40185. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40186. };
  40187. // Methods
  40188. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40189. var engine = this.getEngine();
  40190. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40191. };
  40192. // Target
  40193. TargetCamera.prototype.setTarget = function (target) {
  40194. this.upVector.normalize();
  40195. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40196. this._camMatrix.invert();
  40197. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40198. var vDir = target.subtract(this.position);
  40199. if (vDir.x >= 0.0) {
  40200. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40201. }
  40202. else {
  40203. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40204. }
  40205. this.rotation.z = 0;
  40206. if (isNaN(this.rotation.x)) {
  40207. this.rotation.x = 0;
  40208. }
  40209. if (isNaN(this.rotation.y)) {
  40210. this.rotation.y = 0;
  40211. }
  40212. if (isNaN(this.rotation.z)) {
  40213. this.rotation.z = 0;
  40214. }
  40215. if (this.rotationQuaternion) {
  40216. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40217. }
  40218. };
  40219. /**
  40220. * Return the current target position of the camera. This value is expressed in local space.
  40221. */
  40222. TargetCamera.prototype.getTarget = function () {
  40223. return this._currentTarget;
  40224. };
  40225. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40226. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40227. };
  40228. TargetCamera.prototype._updatePosition = function () {
  40229. if (this.parent) {
  40230. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40231. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40232. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40233. return;
  40234. }
  40235. this.position.addInPlace(this.cameraDirection);
  40236. };
  40237. TargetCamera.prototype._checkInputs = function () {
  40238. var needToMove = this._decideIfNeedsToMove();
  40239. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40240. // Move
  40241. if (needToMove) {
  40242. this._updatePosition();
  40243. }
  40244. // Rotate
  40245. if (needToRotate) {
  40246. this.rotation.x += this.cameraRotation.x;
  40247. this.rotation.y += this.cameraRotation.y;
  40248. //rotate, if quaternion is set and rotation was used
  40249. if (this.rotationQuaternion) {
  40250. var len = this.rotation.lengthSquared();
  40251. if (len) {
  40252. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40253. }
  40254. }
  40255. if (!this.noRotationConstraint) {
  40256. var limit = (Math.PI / 2) * 0.95;
  40257. if (this.rotation.x > limit)
  40258. this.rotation.x = limit;
  40259. if (this.rotation.x < -limit)
  40260. this.rotation.x = -limit;
  40261. }
  40262. }
  40263. // Inertia
  40264. if (needToMove) {
  40265. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40266. this.cameraDirection.x = 0;
  40267. }
  40268. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40269. this.cameraDirection.y = 0;
  40270. }
  40271. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40272. this.cameraDirection.z = 0;
  40273. }
  40274. this.cameraDirection.scaleInPlace(this.inertia);
  40275. }
  40276. if (needToRotate) {
  40277. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40278. this.cameraRotation.x = 0;
  40279. }
  40280. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40281. this.cameraRotation.y = 0;
  40282. }
  40283. this.cameraRotation.scaleInPlace(this.inertia);
  40284. }
  40285. _super.prototype._checkInputs.call(this);
  40286. };
  40287. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40288. if (this.rotationQuaternion) {
  40289. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40290. }
  40291. else {
  40292. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40293. }
  40294. //update the up vector!
  40295. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40296. };
  40297. TargetCamera.prototype._getViewMatrix = function () {
  40298. if (this.lockedTarget) {
  40299. this.setTarget(this._getLockedTargetPosition());
  40300. }
  40301. // Compute
  40302. this._updateCameraRotationMatrix();
  40303. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40304. // Computing target and final matrix
  40305. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40306. if (this.getScene().useRightHandedSystem) {
  40307. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40308. }
  40309. else {
  40310. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40311. }
  40312. return this._viewMatrix;
  40313. };
  40314. /**
  40315. * @override
  40316. * Override Camera.createRigCamera
  40317. */
  40318. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40319. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40320. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40321. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40322. if (!this.rotationQuaternion) {
  40323. this.rotationQuaternion = new BABYLON.Quaternion();
  40324. }
  40325. rigCamera._cameraRigParams = {};
  40326. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40327. }
  40328. return rigCamera;
  40329. }
  40330. return null;
  40331. };
  40332. /**
  40333. * @override
  40334. * Override Camera._updateRigCameras
  40335. */
  40336. TargetCamera.prototype._updateRigCameras = function () {
  40337. var camLeft = this._rigCameras[0];
  40338. var camRight = this._rigCameras[1];
  40339. switch (this.cameraRigMode) {
  40340. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40341. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40342. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40343. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40344. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40345. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40346. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40347. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40348. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40349. camLeft.setTarget(this.getTarget());
  40350. camRight.setTarget(this.getTarget());
  40351. break;
  40352. case BABYLON.Camera.RIG_MODE_VR:
  40353. if (camLeft.rotationQuaternion) {
  40354. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40355. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40356. }
  40357. else {
  40358. camLeft.rotation.copyFrom(this.rotation);
  40359. camRight.rotation.copyFrom(this.rotation);
  40360. }
  40361. camLeft.position.copyFrom(this.position);
  40362. camRight.position.copyFrom(this.position);
  40363. break;
  40364. }
  40365. _super.prototype._updateRigCameras.call(this);
  40366. };
  40367. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40368. if (!this._rigCamTransformMatrix) {
  40369. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40370. }
  40371. var target = this.getTarget();
  40372. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40373. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40374. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40375. };
  40376. TargetCamera.prototype.getClassName = function () {
  40377. return "TargetCamera";
  40378. };
  40379. __decorate([
  40380. BABYLON.serializeAsVector3()
  40381. ], TargetCamera.prototype, "rotation", void 0);
  40382. __decorate([
  40383. BABYLON.serialize()
  40384. ], TargetCamera.prototype, "speed", void 0);
  40385. __decorate([
  40386. BABYLON.serializeAsMeshReference("lockedTargetId")
  40387. ], TargetCamera.prototype, "lockedTarget", void 0);
  40388. return TargetCamera;
  40389. }(BABYLON.Camera));
  40390. BABYLON.TargetCamera = TargetCamera;
  40391. })(BABYLON || (BABYLON = {}));
  40392. //# sourceMappingURL=babylon.targetCamera.js.map
  40393. var BABYLON;
  40394. (function (BABYLON) {
  40395. var FreeCameraMouseInput = /** @class */ (function () {
  40396. function FreeCameraMouseInput(touchEnabled) {
  40397. if (touchEnabled === void 0) { touchEnabled = true; }
  40398. this.touchEnabled = touchEnabled;
  40399. this.buttons = [0, 1, 2];
  40400. this.angularSensibility = 2000.0;
  40401. this.previousPosition = null;
  40402. }
  40403. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40404. var _this = this;
  40405. var engine = this.camera.getEngine();
  40406. if (!this._pointerInput) {
  40407. this._pointerInput = function (p, s) {
  40408. var evt = p.event;
  40409. if (engine.isInVRExclusivePointerMode) {
  40410. return;
  40411. }
  40412. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40413. return;
  40414. }
  40415. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40416. return;
  40417. }
  40418. var srcElement = (evt.srcElement || evt.target);
  40419. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40420. try {
  40421. srcElement.setPointerCapture(evt.pointerId);
  40422. }
  40423. catch (e) {
  40424. //Nothing to do with the error. Execution will continue.
  40425. }
  40426. _this.previousPosition = {
  40427. x: evt.clientX,
  40428. y: evt.clientY
  40429. };
  40430. if (!noPreventDefault) {
  40431. evt.preventDefault();
  40432. element.focus();
  40433. }
  40434. }
  40435. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40436. try {
  40437. srcElement.releasePointerCapture(evt.pointerId);
  40438. }
  40439. catch (e) {
  40440. //Nothing to do with the error.
  40441. }
  40442. _this.previousPosition = null;
  40443. if (!noPreventDefault) {
  40444. evt.preventDefault();
  40445. }
  40446. }
  40447. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40448. if (!_this.previousPosition || engine.isPointerLock) {
  40449. return;
  40450. }
  40451. var offsetX = evt.clientX - _this.previousPosition.x;
  40452. var offsetY = evt.clientY - _this.previousPosition.y;
  40453. if (_this.camera.getScene().useRightHandedSystem) {
  40454. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40455. }
  40456. else {
  40457. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40458. }
  40459. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40460. _this.previousPosition = {
  40461. x: evt.clientX,
  40462. y: evt.clientY
  40463. };
  40464. if (!noPreventDefault) {
  40465. evt.preventDefault();
  40466. }
  40467. }
  40468. };
  40469. }
  40470. this._onMouseMove = function (evt) {
  40471. if (!engine.isPointerLock) {
  40472. return;
  40473. }
  40474. if (engine.isInVRExclusivePointerMode) {
  40475. return;
  40476. }
  40477. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40478. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40479. if (_this.camera.getScene().useRightHandedSystem) {
  40480. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40481. }
  40482. else {
  40483. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40484. }
  40485. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40486. _this.previousPosition = null;
  40487. if (!noPreventDefault) {
  40488. evt.preventDefault();
  40489. }
  40490. };
  40491. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40492. element.addEventListener("mousemove", this._onMouseMove, false);
  40493. };
  40494. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40495. if (this._observer && element) {
  40496. this.camera.getScene().onPointerObservable.remove(this._observer);
  40497. if (this._onMouseMove) {
  40498. element.removeEventListener("mousemove", this._onMouseMove);
  40499. }
  40500. this._observer = null;
  40501. this._onMouseMove = null;
  40502. this.previousPosition = null;
  40503. }
  40504. };
  40505. FreeCameraMouseInput.prototype.getClassName = function () {
  40506. return "FreeCameraMouseInput";
  40507. };
  40508. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40509. return "mouse";
  40510. };
  40511. __decorate([
  40512. BABYLON.serialize()
  40513. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40514. __decorate([
  40515. BABYLON.serialize()
  40516. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40517. return FreeCameraMouseInput;
  40518. }());
  40519. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40520. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40521. })(BABYLON || (BABYLON = {}));
  40522. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40523. var BABYLON;
  40524. (function (BABYLON) {
  40525. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40526. function FreeCameraKeyboardMoveInput() {
  40527. this._keys = new Array();
  40528. this.keysUp = [38];
  40529. this.keysDown = [40];
  40530. this.keysLeft = [37];
  40531. this.keysRight = [39];
  40532. }
  40533. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40534. var _this = this;
  40535. if (this._onCanvasBlurObserver) {
  40536. return;
  40537. }
  40538. this._scene = this.camera.getScene();
  40539. this._engine = this._scene.getEngine();
  40540. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40541. _this._keys = [];
  40542. });
  40543. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40544. var evt = info.event;
  40545. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40546. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40547. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40548. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40549. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40550. var index = _this._keys.indexOf(evt.keyCode);
  40551. if (index === -1) {
  40552. _this._keys.push(evt.keyCode);
  40553. }
  40554. if (!noPreventDefault) {
  40555. evt.preventDefault();
  40556. }
  40557. }
  40558. }
  40559. else {
  40560. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40561. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40562. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40563. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40564. var index = _this._keys.indexOf(evt.keyCode);
  40565. if (index >= 0) {
  40566. _this._keys.splice(index, 1);
  40567. }
  40568. if (!noPreventDefault) {
  40569. evt.preventDefault();
  40570. }
  40571. }
  40572. }
  40573. });
  40574. };
  40575. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40576. if (this._scene) {
  40577. if (this._onKeyboardObserver) {
  40578. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40579. }
  40580. if (this._onCanvasBlurObserver) {
  40581. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40582. }
  40583. this._onKeyboardObserver = null;
  40584. this._onCanvasBlurObserver = null;
  40585. }
  40586. this._keys = [];
  40587. };
  40588. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40589. if (this._onKeyboardObserver) {
  40590. var camera = this.camera;
  40591. // Keyboard
  40592. for (var index = 0; index < this._keys.length; index++) {
  40593. var keyCode = this._keys[index];
  40594. var speed = camera._computeLocalCameraSpeed();
  40595. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40596. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40597. }
  40598. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40599. camera._localDirection.copyFromFloats(0, 0, speed);
  40600. }
  40601. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40602. camera._localDirection.copyFromFloats(speed, 0, 0);
  40603. }
  40604. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40605. camera._localDirection.copyFromFloats(0, 0, -speed);
  40606. }
  40607. if (camera.getScene().useRightHandedSystem) {
  40608. camera._localDirection.z *= -1;
  40609. }
  40610. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40611. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40612. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40613. }
  40614. }
  40615. };
  40616. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40617. return "FreeCameraKeyboardMoveInput";
  40618. };
  40619. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40620. this._keys = [];
  40621. };
  40622. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40623. return "keyboard";
  40624. };
  40625. __decorate([
  40626. BABYLON.serialize()
  40627. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40628. __decorate([
  40629. BABYLON.serialize()
  40630. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40631. __decorate([
  40632. BABYLON.serialize()
  40633. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40634. __decorate([
  40635. BABYLON.serialize()
  40636. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40637. return FreeCameraKeyboardMoveInput;
  40638. }());
  40639. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40640. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40641. })(BABYLON || (BABYLON = {}));
  40642. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40643. var BABYLON;
  40644. (function (BABYLON) {
  40645. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40646. __extends(FreeCameraInputsManager, _super);
  40647. function FreeCameraInputsManager(camera) {
  40648. return _super.call(this, camera) || this;
  40649. }
  40650. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40651. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40652. return this;
  40653. };
  40654. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40655. if (touchEnabled === void 0) { touchEnabled = true; }
  40656. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40657. return this;
  40658. };
  40659. FreeCameraInputsManager.prototype.addGamepad = function () {
  40660. this.add(new BABYLON.FreeCameraGamepadInput());
  40661. return this;
  40662. };
  40663. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40664. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40665. return this;
  40666. };
  40667. FreeCameraInputsManager.prototype.addTouch = function () {
  40668. this.add(new BABYLON.FreeCameraTouchInput());
  40669. return this;
  40670. };
  40671. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40672. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40673. return this;
  40674. };
  40675. return FreeCameraInputsManager;
  40676. }(BABYLON.CameraInputsManager));
  40677. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40678. })(BABYLON || (BABYLON = {}));
  40679. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40680. var BABYLON;
  40681. (function (BABYLON) {
  40682. var FreeCamera = /** @class */ (function (_super) {
  40683. __extends(FreeCamera, _super);
  40684. function FreeCamera(name, position, scene) {
  40685. var _this = _super.call(this, name, position, scene) || this;
  40686. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  40687. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  40688. _this.checkCollisions = false;
  40689. _this.applyGravity = false;
  40690. _this._needMoveForGravity = false;
  40691. _this._oldPosition = BABYLON.Vector3.Zero();
  40692. _this._diffPosition = BABYLON.Vector3.Zero();
  40693. _this._newPosition = BABYLON.Vector3.Zero();
  40694. // Collisions
  40695. _this._collisionMask = -1;
  40696. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40697. if (collidedMesh === void 0) { collidedMesh = null; }
  40698. //TODO move this to the collision coordinator!
  40699. if (_this.getScene().workerCollisions)
  40700. newPosition.multiplyInPlace(_this._collider._radius);
  40701. var updatePosition = function (newPos) {
  40702. _this._newPosition.copyFrom(newPos);
  40703. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  40704. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  40705. _this.position.addInPlace(_this._diffPosition);
  40706. if (_this.onCollide && collidedMesh) {
  40707. _this.onCollide(collidedMesh);
  40708. }
  40709. }
  40710. };
  40711. updatePosition(newPosition);
  40712. };
  40713. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  40714. _this.inputs.addKeyboard().addMouse();
  40715. return _this;
  40716. }
  40717. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  40718. //-- begin properties for backward compatibility for inputs
  40719. /**
  40720. * Gets the input sensibility for a mouse input. (default is 2000.0)
  40721. * Higher values reduce sensitivity.
  40722. */
  40723. get: function () {
  40724. var mouse = this.inputs.attached["mouse"];
  40725. if (mouse)
  40726. return mouse.angularSensibility;
  40727. return 0;
  40728. },
  40729. /**
  40730. * Sets the input sensibility for a mouse input. (default is 2000.0)
  40731. * Higher values reduce sensitivity.
  40732. */
  40733. set: function (value) {
  40734. var mouse = this.inputs.attached["mouse"];
  40735. if (mouse)
  40736. mouse.angularSensibility = value;
  40737. },
  40738. enumerable: true,
  40739. configurable: true
  40740. });
  40741. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  40742. get: function () {
  40743. var keyboard = this.inputs.attached["keyboard"];
  40744. if (keyboard)
  40745. return keyboard.keysUp;
  40746. return [];
  40747. },
  40748. set: function (value) {
  40749. var keyboard = this.inputs.attached["keyboard"];
  40750. if (keyboard)
  40751. keyboard.keysUp = value;
  40752. },
  40753. enumerable: true,
  40754. configurable: true
  40755. });
  40756. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  40757. get: function () {
  40758. var keyboard = this.inputs.attached["keyboard"];
  40759. if (keyboard)
  40760. return keyboard.keysDown;
  40761. return [];
  40762. },
  40763. set: function (value) {
  40764. var keyboard = this.inputs.attached["keyboard"];
  40765. if (keyboard)
  40766. keyboard.keysDown = value;
  40767. },
  40768. enumerable: true,
  40769. configurable: true
  40770. });
  40771. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  40772. get: function () {
  40773. var keyboard = this.inputs.attached["keyboard"];
  40774. if (keyboard)
  40775. return keyboard.keysLeft;
  40776. return [];
  40777. },
  40778. set: function (value) {
  40779. var keyboard = this.inputs.attached["keyboard"];
  40780. if (keyboard)
  40781. keyboard.keysLeft = value;
  40782. },
  40783. enumerable: true,
  40784. configurable: true
  40785. });
  40786. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  40787. get: function () {
  40788. var keyboard = this.inputs.attached["keyboard"];
  40789. if (keyboard)
  40790. return keyboard.keysRight;
  40791. return [];
  40792. },
  40793. set: function (value) {
  40794. var keyboard = this.inputs.attached["keyboard"];
  40795. if (keyboard)
  40796. keyboard.keysRight = value;
  40797. },
  40798. enumerable: true,
  40799. configurable: true
  40800. });
  40801. // Controls
  40802. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  40803. this.inputs.attachElement(element, noPreventDefault);
  40804. };
  40805. FreeCamera.prototype.detachControl = function (element) {
  40806. this.inputs.detachElement(element);
  40807. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40808. this.cameraRotation = new BABYLON.Vector2(0, 0);
  40809. };
  40810. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  40811. get: function () {
  40812. return this._collisionMask;
  40813. },
  40814. set: function (mask) {
  40815. this._collisionMask = !isNaN(mask) ? mask : -1;
  40816. },
  40817. enumerable: true,
  40818. configurable: true
  40819. });
  40820. FreeCamera.prototype._collideWithWorld = function (displacement) {
  40821. var globalPosition;
  40822. if (this.parent) {
  40823. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  40824. }
  40825. else {
  40826. globalPosition = this.position;
  40827. }
  40828. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  40829. this._oldPosition.addInPlace(this.ellipsoidOffset);
  40830. if (!this._collider) {
  40831. this._collider = new BABYLON.Collider();
  40832. }
  40833. this._collider._radius = this.ellipsoid;
  40834. this._collider.collisionMask = this._collisionMask;
  40835. //no need for clone, as long as gravity is not on.
  40836. var actualDisplacement = displacement;
  40837. //add gravity to the direction to prevent the dual-collision checking
  40838. if (this.applyGravity) {
  40839. //this prevents mending with cameraDirection, a global variable of the free camera class.
  40840. actualDisplacement = displacement.add(this.getScene().gravity);
  40841. }
  40842. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40843. };
  40844. FreeCamera.prototype._checkInputs = function () {
  40845. if (!this._localDirection) {
  40846. this._localDirection = BABYLON.Vector3.Zero();
  40847. this._transformedDirection = BABYLON.Vector3.Zero();
  40848. }
  40849. this.inputs.checkInputs();
  40850. _super.prototype._checkInputs.call(this);
  40851. };
  40852. FreeCamera.prototype._decideIfNeedsToMove = function () {
  40853. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40854. };
  40855. FreeCamera.prototype._updatePosition = function () {
  40856. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  40857. this._collideWithWorld(this.cameraDirection);
  40858. }
  40859. else {
  40860. _super.prototype._updatePosition.call(this);
  40861. }
  40862. };
  40863. FreeCamera.prototype.dispose = function () {
  40864. this.inputs.clear();
  40865. _super.prototype.dispose.call(this);
  40866. };
  40867. FreeCamera.prototype.getClassName = function () {
  40868. return "FreeCamera";
  40869. };
  40870. __decorate([
  40871. BABYLON.serializeAsVector3()
  40872. ], FreeCamera.prototype, "ellipsoid", void 0);
  40873. __decorate([
  40874. BABYLON.serializeAsVector3()
  40875. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  40876. __decorate([
  40877. BABYLON.serialize()
  40878. ], FreeCamera.prototype, "checkCollisions", void 0);
  40879. __decorate([
  40880. BABYLON.serialize()
  40881. ], FreeCamera.prototype, "applyGravity", void 0);
  40882. return FreeCamera;
  40883. }(BABYLON.TargetCamera));
  40884. BABYLON.FreeCamera = FreeCamera;
  40885. })(BABYLON || (BABYLON = {}));
  40886. //# sourceMappingURL=babylon.freeCamera.js.map
  40887. var BABYLON;
  40888. (function (BABYLON) {
  40889. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  40890. function ArcRotateCameraKeyboardMoveInput() {
  40891. this._keys = new Array();
  40892. this.keysUp = [38];
  40893. this.keysDown = [40];
  40894. this.keysLeft = [37];
  40895. this.keysRight = [39];
  40896. this.keysReset = [220];
  40897. this.panningSensibility = 50.0;
  40898. this.zoomingSensibility = 25.0;
  40899. this.useAltToZoom = true;
  40900. }
  40901. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40902. var _this = this;
  40903. if (this._onCanvasBlurObserver) {
  40904. return;
  40905. }
  40906. this._scene = this.camera.getScene();
  40907. this._engine = this._scene.getEngine();
  40908. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40909. _this._keys = [];
  40910. });
  40911. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40912. var evt = info.event;
  40913. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40914. _this._ctrlPressed = evt.ctrlKey;
  40915. _this._altPressed = evt.altKey;
  40916. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40917. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40918. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40919. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40920. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40921. var index = _this._keys.indexOf(evt.keyCode);
  40922. if (index === -1) {
  40923. _this._keys.push(evt.keyCode);
  40924. }
  40925. if (evt.preventDefault) {
  40926. if (!noPreventDefault) {
  40927. evt.preventDefault();
  40928. }
  40929. }
  40930. }
  40931. }
  40932. else {
  40933. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40934. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40935. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40936. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40937. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40938. var index = _this._keys.indexOf(evt.keyCode);
  40939. if (index >= 0) {
  40940. _this._keys.splice(index, 1);
  40941. }
  40942. if (evt.preventDefault) {
  40943. if (!noPreventDefault) {
  40944. evt.preventDefault();
  40945. }
  40946. }
  40947. }
  40948. }
  40949. });
  40950. };
  40951. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40952. if (this._scene) {
  40953. if (this._onKeyboardObserver) {
  40954. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40955. }
  40956. if (this._onCanvasBlurObserver) {
  40957. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40958. }
  40959. this._onKeyboardObserver = null;
  40960. this._onCanvasBlurObserver = null;
  40961. }
  40962. this._keys = [];
  40963. };
  40964. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40965. if (this._onKeyboardObserver) {
  40966. var camera = this.camera;
  40967. for (var index = 0; index < this._keys.length; index++) {
  40968. var keyCode = this._keys[index];
  40969. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40970. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40971. camera.inertialPanningX -= 1 / this.panningSensibility;
  40972. }
  40973. else {
  40974. camera.inertialAlphaOffset -= 0.01;
  40975. }
  40976. }
  40977. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40978. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40979. camera.inertialPanningY += 1 / this.panningSensibility;
  40980. }
  40981. else if (this._altPressed && this.useAltToZoom) {
  40982. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  40983. }
  40984. else {
  40985. camera.inertialBetaOffset -= 0.01;
  40986. }
  40987. }
  40988. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40989. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40990. camera.inertialPanningX += 1 / this.panningSensibility;
  40991. }
  40992. else {
  40993. camera.inertialAlphaOffset += 0.01;
  40994. }
  40995. }
  40996. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40997. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  40998. camera.inertialPanningY -= 1 / this.panningSensibility;
  40999. }
  41000. else if (this._altPressed && this.useAltToZoom) {
  41001. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41002. }
  41003. else {
  41004. camera.inertialBetaOffset += 0.01;
  41005. }
  41006. }
  41007. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41008. camera.restoreState();
  41009. }
  41010. }
  41011. }
  41012. };
  41013. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41014. return "ArcRotateCameraKeyboardMoveInput";
  41015. };
  41016. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41017. return "keyboard";
  41018. };
  41019. __decorate([
  41020. BABYLON.serialize()
  41021. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41022. __decorate([
  41023. BABYLON.serialize()
  41024. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41025. __decorate([
  41026. BABYLON.serialize()
  41027. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41028. __decorate([
  41029. BABYLON.serialize()
  41030. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41031. __decorate([
  41032. BABYLON.serialize()
  41033. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41034. __decorate([
  41035. BABYLON.serialize()
  41036. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41037. __decorate([
  41038. BABYLON.serialize()
  41039. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41040. __decorate([
  41041. BABYLON.serialize()
  41042. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41043. return ArcRotateCameraKeyboardMoveInput;
  41044. }());
  41045. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41046. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41047. })(BABYLON || (BABYLON = {}));
  41048. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41049. var BABYLON;
  41050. (function (BABYLON) {
  41051. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41052. function ArcRotateCameraMouseWheelInput() {
  41053. this.wheelPrecision = 3.0;
  41054. /**
  41055. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41056. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41057. */
  41058. this.wheelDeltaPercentage = 0;
  41059. }
  41060. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41061. var _this = this;
  41062. this._wheel = function (p, s) {
  41063. //sanity check - this should be a PointerWheel event.
  41064. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41065. return;
  41066. var event = p.event;
  41067. var delta = 0;
  41068. if (event.wheelDelta) {
  41069. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41070. }
  41071. else if (event.detail) {
  41072. delta = -event.detail / _this.wheelPrecision;
  41073. }
  41074. if (delta)
  41075. _this.camera.inertialRadiusOffset += delta;
  41076. if (event.preventDefault) {
  41077. if (!noPreventDefault) {
  41078. event.preventDefault();
  41079. }
  41080. }
  41081. };
  41082. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41083. };
  41084. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41085. if (this._observer && element) {
  41086. this.camera.getScene().onPointerObservable.remove(this._observer);
  41087. this._observer = null;
  41088. this._wheel = null;
  41089. }
  41090. };
  41091. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41092. return "ArcRotateCameraMouseWheelInput";
  41093. };
  41094. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41095. return "mousewheel";
  41096. };
  41097. __decorate([
  41098. BABYLON.serialize()
  41099. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41100. __decorate([
  41101. BABYLON.serialize()
  41102. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41103. return ArcRotateCameraMouseWheelInput;
  41104. }());
  41105. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41106. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41107. })(BABYLON || (BABYLON = {}));
  41108. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41109. var BABYLON;
  41110. (function (BABYLON) {
  41111. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41112. function ArcRotateCameraPointersInput() {
  41113. this.buttons = [0, 1, 2];
  41114. this.angularSensibilityX = 1000.0;
  41115. this.angularSensibilityY = 1000.0;
  41116. this.pinchPrecision = 12.0;
  41117. /**
  41118. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41119. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41120. */
  41121. this.pinchDeltaPercentage = 0;
  41122. this.panningSensibility = 1000.0;
  41123. this.multiTouchPanning = true;
  41124. this.multiTouchPanAndZoom = true;
  41125. this._isPanClick = false;
  41126. this.pinchInwards = true;
  41127. }
  41128. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41129. var _this = this;
  41130. var engine = this.camera.getEngine();
  41131. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41132. var pointA = null;
  41133. var pointB = null;
  41134. var previousPinchSquaredDistance = 0;
  41135. var initialDistance = 0;
  41136. var twoFingerActivityCount = 0;
  41137. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41138. this._pointerInput = function (p, s) {
  41139. var evt = p.event;
  41140. var isTouch = p.event.pointerType === "touch";
  41141. if (engine.isInVRExclusivePointerMode) {
  41142. return;
  41143. }
  41144. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41145. return;
  41146. }
  41147. var srcElement = (evt.srcElement || evt.target);
  41148. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41149. try {
  41150. srcElement.setPointerCapture(evt.pointerId);
  41151. }
  41152. catch (e) {
  41153. //Nothing to do with the error. Execution will continue.
  41154. }
  41155. // Manage panning with pan button click
  41156. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41157. // manage pointers
  41158. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41159. if (pointA === null) {
  41160. pointA = cacheSoloPointer;
  41161. }
  41162. else if (pointB === null) {
  41163. pointB = cacheSoloPointer;
  41164. }
  41165. if (!noPreventDefault) {
  41166. evt.preventDefault();
  41167. element.focus();
  41168. }
  41169. }
  41170. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41171. _this.camera.restoreState();
  41172. }
  41173. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41174. try {
  41175. srcElement.releasePointerCapture(evt.pointerId);
  41176. }
  41177. catch (e) {
  41178. //Nothing to do with the error.
  41179. }
  41180. cacheSoloPointer = null;
  41181. previousPinchSquaredDistance = 0;
  41182. previousMultiTouchPanPosition.isPaning = false;
  41183. previousMultiTouchPanPosition.isPinching = false;
  41184. twoFingerActivityCount = 0;
  41185. initialDistance = 0;
  41186. if (!isTouch) {
  41187. pointB = null; // Mouse and pen are mono pointer
  41188. }
  41189. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41190. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41191. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41192. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41193. if (engine.badOS) {
  41194. pointA = pointB = null;
  41195. }
  41196. else {
  41197. //only remove the impacted pointer in case of multitouch allowing on most
  41198. //platforms switching from rotate to zoom and pan seamlessly.
  41199. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41200. pointA = pointB;
  41201. pointB = null;
  41202. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41203. }
  41204. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41205. pointB = null;
  41206. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41207. }
  41208. else {
  41209. pointA = pointB = null;
  41210. }
  41211. }
  41212. if (!noPreventDefault) {
  41213. evt.preventDefault();
  41214. }
  41215. }
  41216. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41217. if (!noPreventDefault) {
  41218. evt.preventDefault();
  41219. }
  41220. // One button down
  41221. if (pointA && pointB === null && cacheSoloPointer) {
  41222. if (_this.panningSensibility !== 0 &&
  41223. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41224. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41225. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41226. }
  41227. else {
  41228. var offsetX = evt.clientX - cacheSoloPointer.x;
  41229. var offsetY = evt.clientY - cacheSoloPointer.y;
  41230. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41231. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41232. }
  41233. cacheSoloPointer.x = evt.clientX;
  41234. cacheSoloPointer.y = evt.clientY;
  41235. }
  41236. else if (pointA && pointB) {
  41237. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41238. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41239. ed.x = evt.clientX;
  41240. ed.y = evt.clientY;
  41241. var direction = _this.pinchInwards ? 1 : -1;
  41242. var distX = pointA.x - pointB.x;
  41243. var distY = pointA.y - pointB.y;
  41244. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41245. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41246. if (previousPinchSquaredDistance === 0) {
  41247. initialDistance = pinchDistance;
  41248. previousPinchSquaredDistance = pinchSquaredDistance;
  41249. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41250. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41251. return;
  41252. }
  41253. if (_this.multiTouchPanAndZoom) {
  41254. if (_this.pinchDeltaPercentage) {
  41255. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41256. }
  41257. else {
  41258. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41259. (_this.pinchPrecision *
  41260. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41261. direction);
  41262. }
  41263. if (_this.panningSensibility !== 0) {
  41264. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41265. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41266. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41267. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41268. previousMultiTouchPanPosition.x = pointersCenterX;
  41269. previousMultiTouchPanPosition.y = pointersCenterY;
  41270. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41271. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41272. }
  41273. }
  41274. else {
  41275. twoFingerActivityCount++;
  41276. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41277. if (_this.pinchDeltaPercentage) {
  41278. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41279. }
  41280. else {
  41281. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41282. (_this.pinchPrecision *
  41283. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41284. direction);
  41285. }
  41286. previousMultiTouchPanPosition.isPaning = false;
  41287. previousMultiTouchPanPosition.isPinching = true;
  41288. }
  41289. else {
  41290. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41291. if (!previousMultiTouchPanPosition.isPaning) {
  41292. previousMultiTouchPanPosition.isPaning = true;
  41293. previousMultiTouchPanPosition.isPinching = false;
  41294. previousMultiTouchPanPosition.x = ed.x;
  41295. previousMultiTouchPanPosition.y = ed.y;
  41296. return;
  41297. }
  41298. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41299. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41300. }
  41301. }
  41302. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41303. previousMultiTouchPanPosition.x = ed.x;
  41304. previousMultiTouchPanPosition.y = ed.y;
  41305. }
  41306. }
  41307. previousPinchSquaredDistance = pinchSquaredDistance;
  41308. }
  41309. }
  41310. };
  41311. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41312. this._onContextMenu = function (evt) {
  41313. evt.preventDefault();
  41314. };
  41315. if (!this.camera._useCtrlForPanning) {
  41316. element.addEventListener("contextmenu", this._onContextMenu, false);
  41317. }
  41318. this._onLostFocus = function () {
  41319. //this._keys = [];
  41320. pointA = pointB = null;
  41321. previousPinchSquaredDistance = 0;
  41322. previousMultiTouchPanPosition.isPaning = false;
  41323. previousMultiTouchPanPosition.isPinching = false;
  41324. twoFingerActivityCount = 0;
  41325. cacheSoloPointer = null;
  41326. initialDistance = 0;
  41327. };
  41328. this._onMouseMove = function (evt) {
  41329. if (!engine.isPointerLock) {
  41330. return;
  41331. }
  41332. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41333. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41334. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41335. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41336. if (!noPreventDefault) {
  41337. evt.preventDefault();
  41338. }
  41339. };
  41340. this._onGestureStart = function (e) {
  41341. if (window.MSGesture === undefined) {
  41342. return;
  41343. }
  41344. if (!_this._MSGestureHandler) {
  41345. _this._MSGestureHandler = new MSGesture();
  41346. _this._MSGestureHandler.target = element;
  41347. }
  41348. _this._MSGestureHandler.addPointer(e.pointerId);
  41349. };
  41350. this._onGesture = function (e) {
  41351. _this.camera.radius *= e.scale;
  41352. if (e.preventDefault) {
  41353. if (!noPreventDefault) {
  41354. e.stopPropagation();
  41355. e.preventDefault();
  41356. }
  41357. }
  41358. };
  41359. element.addEventListener("mousemove", this._onMouseMove, false);
  41360. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41361. element.addEventListener("MSGestureChange", this._onGesture, false);
  41362. BABYLON.Tools.RegisterTopRootEvents([
  41363. { name: "blur", handler: this._onLostFocus }
  41364. ]);
  41365. };
  41366. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41367. if (this._onLostFocus) {
  41368. BABYLON.Tools.UnregisterTopRootEvents([
  41369. { name: "blur", handler: this._onLostFocus }
  41370. ]);
  41371. }
  41372. if (element && this._observer) {
  41373. this.camera.getScene().onPointerObservable.remove(this._observer);
  41374. this._observer = null;
  41375. if (this._onContextMenu) {
  41376. element.removeEventListener("contextmenu", this._onContextMenu);
  41377. }
  41378. if (this._onMouseMove) {
  41379. element.removeEventListener("mousemove", this._onMouseMove);
  41380. }
  41381. if (this._onGestureStart) {
  41382. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41383. }
  41384. if (this._onGesture) {
  41385. element.removeEventListener("MSGestureChange", this._onGesture);
  41386. }
  41387. this._isPanClick = false;
  41388. this.pinchInwards = true;
  41389. this._onMouseMove = null;
  41390. this._onGestureStart = null;
  41391. this._onGesture = null;
  41392. this._MSGestureHandler = null;
  41393. this._onLostFocus = null;
  41394. this._onContextMenu = null;
  41395. }
  41396. };
  41397. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41398. return "ArcRotateCameraPointersInput";
  41399. };
  41400. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41401. return "pointers";
  41402. };
  41403. __decorate([
  41404. BABYLON.serialize()
  41405. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41406. __decorate([
  41407. BABYLON.serialize()
  41408. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41409. __decorate([
  41410. BABYLON.serialize()
  41411. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41412. __decorate([
  41413. BABYLON.serialize()
  41414. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41415. __decorate([
  41416. BABYLON.serialize()
  41417. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41418. __decorate([
  41419. BABYLON.serialize()
  41420. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41421. __decorate([
  41422. BABYLON.serialize()
  41423. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41424. __decorate([
  41425. BABYLON.serialize()
  41426. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41427. return ArcRotateCameraPointersInput;
  41428. }());
  41429. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41430. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41431. })(BABYLON || (BABYLON = {}));
  41432. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41433. var BABYLON;
  41434. (function (BABYLON) {
  41435. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41436. __extends(ArcRotateCameraInputsManager, _super);
  41437. function ArcRotateCameraInputsManager(camera) {
  41438. return _super.call(this, camera) || this;
  41439. }
  41440. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41441. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41442. return this;
  41443. };
  41444. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41445. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41446. return this;
  41447. };
  41448. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41449. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41450. return this;
  41451. };
  41452. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41453. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41454. return this;
  41455. };
  41456. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41457. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41458. return this;
  41459. };
  41460. return ArcRotateCameraInputsManager;
  41461. }(BABYLON.CameraInputsManager));
  41462. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41463. })(BABYLON || (BABYLON = {}));
  41464. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41465. var BABYLON;
  41466. (function (BABYLON) {
  41467. var ArcRotateCamera = /** @class */ (function (_super) {
  41468. __extends(ArcRotateCamera, _super);
  41469. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41470. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41471. _this.inertialAlphaOffset = 0;
  41472. _this.inertialBetaOffset = 0;
  41473. _this.inertialRadiusOffset = 0;
  41474. _this.lowerAlphaLimit = null;
  41475. _this.upperAlphaLimit = null;
  41476. _this.lowerBetaLimit = 0.01;
  41477. _this.upperBetaLimit = Math.PI;
  41478. _this.lowerRadiusLimit = null;
  41479. _this.upperRadiusLimit = null;
  41480. _this.inertialPanningX = 0;
  41481. _this.inertialPanningY = 0;
  41482. _this.pinchToPanMaxDistance = 20;
  41483. _this.panningDistanceLimit = null;
  41484. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41485. _this.panningInertia = 0.9;
  41486. //-- end properties for backward compatibility for inputs
  41487. _this.zoomOnFactor = 1;
  41488. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41489. _this.allowUpsideDown = true;
  41490. _this._viewMatrix = new BABYLON.Matrix();
  41491. // Panning
  41492. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41493. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41494. _this.checkCollisions = false;
  41495. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41496. _this._previousPosition = BABYLON.Vector3.Zero();
  41497. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41498. _this._newPosition = BABYLON.Vector3.Zero();
  41499. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41500. if (collidedMesh === void 0) { collidedMesh = null; }
  41501. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41502. newPosition.multiplyInPlace(_this._collider._radius);
  41503. }
  41504. if (!collidedMesh) {
  41505. _this._previousPosition.copyFrom(_this.position);
  41506. }
  41507. else {
  41508. _this.setPosition(newPosition);
  41509. if (_this.onCollide) {
  41510. _this.onCollide(collidedMesh);
  41511. }
  41512. }
  41513. // Recompute because of constraints
  41514. var cosa = Math.cos(_this.alpha);
  41515. var sina = Math.sin(_this.alpha);
  41516. var cosb = Math.cos(_this.beta);
  41517. var sinb = Math.sin(_this.beta);
  41518. if (sinb === 0) {
  41519. sinb = 0.0001;
  41520. }
  41521. var target = _this._getTargetPosition();
  41522. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41523. _this.position.copyFrom(_this._newPosition);
  41524. var up = _this.upVector;
  41525. if (_this.allowUpsideDown && _this.beta < 0) {
  41526. up = up.clone();
  41527. up = up.negate();
  41528. }
  41529. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41530. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41531. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41532. _this._collisionTriggered = false;
  41533. };
  41534. _this._target = BABYLON.Vector3.Zero();
  41535. if (target) {
  41536. _this.setTarget(target);
  41537. }
  41538. _this.alpha = alpha;
  41539. _this.beta = beta;
  41540. _this.radius = radius;
  41541. _this.getViewMatrix();
  41542. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41543. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41544. return _this;
  41545. }
  41546. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41547. get: function () {
  41548. return this._target;
  41549. },
  41550. set: function (value) {
  41551. this.setTarget(value);
  41552. },
  41553. enumerable: true,
  41554. configurable: true
  41555. });
  41556. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41557. //-- begin properties for backward compatibility for inputs
  41558. get: function () {
  41559. var pointers = this.inputs.attached["pointers"];
  41560. if (pointers)
  41561. return pointers.angularSensibilityX;
  41562. return 0;
  41563. },
  41564. set: function (value) {
  41565. var pointers = this.inputs.attached["pointers"];
  41566. if (pointers) {
  41567. pointers.angularSensibilityX = value;
  41568. }
  41569. },
  41570. enumerable: true,
  41571. configurable: true
  41572. });
  41573. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41574. get: function () {
  41575. var pointers = this.inputs.attached["pointers"];
  41576. if (pointers)
  41577. return pointers.angularSensibilityY;
  41578. return 0;
  41579. },
  41580. set: function (value) {
  41581. var pointers = this.inputs.attached["pointers"];
  41582. if (pointers) {
  41583. pointers.angularSensibilityY = value;
  41584. }
  41585. },
  41586. enumerable: true,
  41587. configurable: true
  41588. });
  41589. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41590. get: function () {
  41591. var pointers = this.inputs.attached["pointers"];
  41592. if (pointers)
  41593. return pointers.pinchPrecision;
  41594. return 0;
  41595. },
  41596. set: function (value) {
  41597. var pointers = this.inputs.attached["pointers"];
  41598. if (pointers) {
  41599. pointers.pinchPrecision = value;
  41600. }
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41606. get: function () {
  41607. var pointers = this.inputs.attached["pointers"];
  41608. if (pointers)
  41609. return pointers.pinchDeltaPercentage;
  41610. return 0;
  41611. },
  41612. set: function (value) {
  41613. var pointers = this.inputs.attached["pointers"];
  41614. if (pointers) {
  41615. pointers.pinchDeltaPercentage = value;
  41616. }
  41617. },
  41618. enumerable: true,
  41619. configurable: true
  41620. });
  41621. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41622. get: function () {
  41623. var pointers = this.inputs.attached["pointers"];
  41624. if (pointers)
  41625. return pointers.panningSensibility;
  41626. return 0;
  41627. },
  41628. set: function (value) {
  41629. var pointers = this.inputs.attached["pointers"];
  41630. if (pointers) {
  41631. pointers.panningSensibility = value;
  41632. }
  41633. },
  41634. enumerable: true,
  41635. configurable: true
  41636. });
  41637. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41638. get: function () {
  41639. var keyboard = this.inputs.attached["keyboard"];
  41640. if (keyboard)
  41641. return keyboard.keysUp;
  41642. return [];
  41643. },
  41644. set: function (value) {
  41645. var keyboard = this.inputs.attached["keyboard"];
  41646. if (keyboard)
  41647. keyboard.keysUp = value;
  41648. },
  41649. enumerable: true,
  41650. configurable: true
  41651. });
  41652. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41653. get: function () {
  41654. var keyboard = this.inputs.attached["keyboard"];
  41655. if (keyboard)
  41656. return keyboard.keysDown;
  41657. return [];
  41658. },
  41659. set: function (value) {
  41660. var keyboard = this.inputs.attached["keyboard"];
  41661. if (keyboard)
  41662. keyboard.keysDown = value;
  41663. },
  41664. enumerable: true,
  41665. configurable: true
  41666. });
  41667. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41668. get: function () {
  41669. var keyboard = this.inputs.attached["keyboard"];
  41670. if (keyboard)
  41671. return keyboard.keysLeft;
  41672. return [];
  41673. },
  41674. set: function (value) {
  41675. var keyboard = this.inputs.attached["keyboard"];
  41676. if (keyboard)
  41677. keyboard.keysLeft = value;
  41678. },
  41679. enumerable: true,
  41680. configurable: true
  41681. });
  41682. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41683. get: function () {
  41684. var keyboard = this.inputs.attached["keyboard"];
  41685. if (keyboard)
  41686. return keyboard.keysRight;
  41687. return [];
  41688. },
  41689. set: function (value) {
  41690. var keyboard = this.inputs.attached["keyboard"];
  41691. if (keyboard)
  41692. keyboard.keysRight = value;
  41693. },
  41694. enumerable: true,
  41695. configurable: true
  41696. });
  41697. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  41698. get: function () {
  41699. var mousewheel = this.inputs.attached["mousewheel"];
  41700. if (mousewheel)
  41701. return mousewheel.wheelPrecision;
  41702. return 0;
  41703. },
  41704. set: function (value) {
  41705. var mousewheel = this.inputs.attached["mousewheel"];
  41706. if (mousewheel)
  41707. mousewheel.wheelPrecision = value;
  41708. },
  41709. enumerable: true,
  41710. configurable: true
  41711. });
  41712. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  41713. get: function () {
  41714. var mousewheel = this.inputs.attached["mousewheel"];
  41715. if (mousewheel)
  41716. return mousewheel.wheelDeltaPercentage;
  41717. return 0;
  41718. },
  41719. set: function (value) {
  41720. var mousewheel = this.inputs.attached["mousewheel"];
  41721. if (mousewheel)
  41722. mousewheel.wheelDeltaPercentage = value;
  41723. },
  41724. enumerable: true,
  41725. configurable: true
  41726. });
  41727. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  41728. get: function () {
  41729. return this._bouncingBehavior;
  41730. },
  41731. enumerable: true,
  41732. configurable: true
  41733. });
  41734. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  41735. get: function () {
  41736. return this._bouncingBehavior != null;
  41737. },
  41738. set: function (value) {
  41739. if (value === this.useBouncingBehavior) {
  41740. return;
  41741. }
  41742. if (value) {
  41743. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  41744. this.addBehavior(this._bouncingBehavior);
  41745. }
  41746. else if (this._bouncingBehavior) {
  41747. this.removeBehavior(this._bouncingBehavior);
  41748. this._bouncingBehavior = null;
  41749. }
  41750. },
  41751. enumerable: true,
  41752. configurable: true
  41753. });
  41754. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  41755. get: function () {
  41756. return this._framingBehavior;
  41757. },
  41758. enumerable: true,
  41759. configurable: true
  41760. });
  41761. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  41762. get: function () {
  41763. return this._framingBehavior != null;
  41764. },
  41765. set: function (value) {
  41766. if (value === this.useFramingBehavior) {
  41767. return;
  41768. }
  41769. if (value) {
  41770. this._framingBehavior = new BABYLON.FramingBehavior();
  41771. this.addBehavior(this._framingBehavior);
  41772. }
  41773. else if (this._framingBehavior) {
  41774. this.removeBehavior(this._framingBehavior);
  41775. this._framingBehavior = null;
  41776. }
  41777. },
  41778. enumerable: true,
  41779. configurable: true
  41780. });
  41781. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  41782. get: function () {
  41783. return this._autoRotationBehavior;
  41784. },
  41785. enumerable: true,
  41786. configurable: true
  41787. });
  41788. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  41789. get: function () {
  41790. return this._autoRotationBehavior != null;
  41791. },
  41792. set: function (value) {
  41793. if (value === this.useAutoRotationBehavior) {
  41794. return;
  41795. }
  41796. if (value) {
  41797. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  41798. this.addBehavior(this._autoRotationBehavior);
  41799. }
  41800. else if (this._autoRotationBehavior) {
  41801. this.removeBehavior(this._autoRotationBehavior);
  41802. this._autoRotationBehavior = null;
  41803. }
  41804. },
  41805. enumerable: true,
  41806. configurable: true
  41807. });
  41808. // Cache
  41809. ArcRotateCamera.prototype._initCache = function () {
  41810. _super.prototype._initCache.call(this);
  41811. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  41812. this._cache.alpha = undefined;
  41813. this._cache.beta = undefined;
  41814. this._cache.radius = undefined;
  41815. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  41816. };
  41817. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  41818. if (!ignoreParentClass) {
  41819. _super.prototype._updateCache.call(this);
  41820. }
  41821. this._cache._target.copyFrom(this._getTargetPosition());
  41822. this._cache.alpha = this.alpha;
  41823. this._cache.beta = this.beta;
  41824. this._cache.radius = this.radius;
  41825. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  41826. };
  41827. ArcRotateCamera.prototype._getTargetPosition = function () {
  41828. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  41829. var pos = this._targetHost.getAbsolutePosition();
  41830. if (this._targetBoundingCenter) {
  41831. pos.addToRef(this._targetBoundingCenter, this._target);
  41832. }
  41833. else {
  41834. this._target.copyFrom(pos);
  41835. }
  41836. }
  41837. var lockedTargetPosition = this._getLockedTargetPosition();
  41838. if (lockedTargetPosition) {
  41839. return lockedTargetPosition;
  41840. }
  41841. return this._target;
  41842. };
  41843. ArcRotateCamera.prototype.storeState = function () {
  41844. this._storedAlpha = this.alpha;
  41845. this._storedBeta = this.beta;
  41846. this._storedRadius = this.radius;
  41847. this._storedTarget = this._getTargetPosition().clone();
  41848. return _super.prototype.storeState.call(this);
  41849. };
  41850. /**
  41851. * Restored camera state. You must call storeState() first
  41852. */
  41853. ArcRotateCamera.prototype._restoreStateValues = function () {
  41854. if (!_super.prototype._restoreStateValues.call(this)) {
  41855. return false;
  41856. }
  41857. this.alpha = this._storedAlpha;
  41858. this.beta = this._storedBeta;
  41859. this.radius = this._storedRadius;
  41860. this.setTarget(this._storedTarget.clone());
  41861. this.inertialAlphaOffset = 0;
  41862. this.inertialBetaOffset = 0;
  41863. this.inertialRadiusOffset = 0;
  41864. this.inertialPanningX = 0;
  41865. this.inertialPanningY = 0;
  41866. return true;
  41867. };
  41868. // Synchronized
  41869. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  41870. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  41871. return false;
  41872. return this._cache._target.equals(this._getTargetPosition())
  41873. && this._cache.alpha === this.alpha
  41874. && this._cache.beta === this.beta
  41875. && this._cache.radius === this.radius
  41876. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  41877. };
  41878. // Methods
  41879. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  41880. var _this = this;
  41881. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  41882. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  41883. this._useCtrlForPanning = useCtrlForPanning;
  41884. this._panningMouseButton = panningMouseButton;
  41885. this.inputs.attachElement(element, noPreventDefault);
  41886. this._reset = function () {
  41887. _this.inertialAlphaOffset = 0;
  41888. _this.inertialBetaOffset = 0;
  41889. _this.inertialRadiusOffset = 0;
  41890. _this.inertialPanningX = 0;
  41891. _this.inertialPanningY = 0;
  41892. };
  41893. };
  41894. ArcRotateCamera.prototype.detachControl = function (element) {
  41895. this.inputs.detachElement(element);
  41896. if (this._reset) {
  41897. this._reset();
  41898. }
  41899. };
  41900. ArcRotateCamera.prototype._checkInputs = function () {
  41901. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  41902. if (this._collisionTriggered) {
  41903. return;
  41904. }
  41905. this.inputs.checkInputs();
  41906. // Inertia
  41907. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  41908. if (this.getScene().useRightHandedSystem) {
  41909. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41910. }
  41911. else {
  41912. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41913. }
  41914. this.beta += this.inertialBetaOffset;
  41915. this.radius -= this.inertialRadiusOffset;
  41916. this.inertialAlphaOffset *= this.inertia;
  41917. this.inertialBetaOffset *= this.inertia;
  41918. this.inertialRadiusOffset *= this.inertia;
  41919. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  41920. this.inertialAlphaOffset = 0;
  41921. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  41922. this.inertialBetaOffset = 0;
  41923. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  41924. this.inertialRadiusOffset = 0;
  41925. }
  41926. // Panning inertia
  41927. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  41928. if (!this._localDirection) {
  41929. this._localDirection = BABYLON.Vector3.Zero();
  41930. this._transformedDirection = BABYLON.Vector3.Zero();
  41931. }
  41932. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  41933. this._localDirection.multiplyInPlace(this.panningAxis);
  41934. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  41935. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  41936. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  41937. if (!this.panningAxis.y) {
  41938. this._transformedDirection.y = 0;
  41939. }
  41940. if (!this._targetHost) {
  41941. if (this.panningDistanceLimit) {
  41942. this._transformedDirection.addInPlace(this._target);
  41943. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  41944. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  41945. this._target.copyFrom(this._transformedDirection);
  41946. }
  41947. }
  41948. else {
  41949. this._target.addInPlace(this._transformedDirection);
  41950. }
  41951. }
  41952. this.inertialPanningX *= this.panningInertia;
  41953. this.inertialPanningY *= this.panningInertia;
  41954. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  41955. this.inertialPanningX = 0;
  41956. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  41957. this.inertialPanningY = 0;
  41958. }
  41959. // Limits
  41960. this._checkLimits();
  41961. _super.prototype._checkInputs.call(this);
  41962. };
  41963. ArcRotateCamera.prototype._checkLimits = function () {
  41964. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  41965. if (this.allowUpsideDown && this.beta > Math.PI) {
  41966. this.beta = this.beta - (2 * Math.PI);
  41967. }
  41968. }
  41969. else {
  41970. if (this.beta < this.lowerBetaLimit) {
  41971. this.beta = this.lowerBetaLimit;
  41972. }
  41973. }
  41974. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  41975. if (this.allowUpsideDown && this.beta < -Math.PI) {
  41976. this.beta = this.beta + (2 * Math.PI);
  41977. }
  41978. }
  41979. else {
  41980. if (this.beta > this.upperBetaLimit) {
  41981. this.beta = this.upperBetaLimit;
  41982. }
  41983. }
  41984. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  41985. this.alpha = this.lowerAlphaLimit;
  41986. }
  41987. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  41988. this.alpha = this.upperAlphaLimit;
  41989. }
  41990. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  41991. this.radius = this.lowerRadiusLimit;
  41992. }
  41993. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  41994. this.radius = this.upperRadiusLimit;
  41995. }
  41996. };
  41997. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  41998. var radiusv3 = this.position.subtract(this._getTargetPosition());
  41999. this.radius = radiusv3.length();
  42000. if (this.radius === 0) {
  42001. this.radius = 0.0001; // Just to avoid division by zero
  42002. }
  42003. // Alpha
  42004. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42005. if (radiusv3.z < 0) {
  42006. this.alpha = 2 * Math.PI - this.alpha;
  42007. }
  42008. // Beta
  42009. this.beta = Math.acos(radiusv3.y / this.radius);
  42010. this._checkLimits();
  42011. };
  42012. ArcRotateCamera.prototype.setPosition = function (position) {
  42013. if (this.position.equals(position)) {
  42014. return;
  42015. }
  42016. this.position.copyFrom(position);
  42017. this.rebuildAnglesAndRadius();
  42018. };
  42019. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42020. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42021. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42022. if (target.getBoundingInfo) {
  42023. if (toBoundingCenter) {
  42024. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42025. }
  42026. else {
  42027. this._targetBoundingCenter = null;
  42028. }
  42029. this._targetHost = target;
  42030. this._target = this._getTargetPosition();
  42031. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42032. }
  42033. else {
  42034. var newTarget = target;
  42035. var currentTarget = this._getTargetPosition();
  42036. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42037. return;
  42038. }
  42039. this._targetHost = null;
  42040. this._target = newTarget;
  42041. this._targetBoundingCenter = null;
  42042. this.onMeshTargetChangedObservable.notifyObservers(null);
  42043. }
  42044. this.rebuildAnglesAndRadius();
  42045. };
  42046. ArcRotateCamera.prototype._getViewMatrix = function () {
  42047. // Compute
  42048. var cosa = Math.cos(this.alpha);
  42049. var sina = Math.sin(this.alpha);
  42050. var cosb = Math.cos(this.beta);
  42051. var sinb = Math.sin(this.beta);
  42052. if (sinb === 0) {
  42053. sinb = 0.0001;
  42054. }
  42055. var target = this._getTargetPosition();
  42056. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42057. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42058. if (!this._collider) {
  42059. this._collider = new BABYLON.Collider();
  42060. }
  42061. this._collider._radius = this.collisionRadius;
  42062. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42063. this._collisionTriggered = true;
  42064. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42065. }
  42066. else {
  42067. this.position.copyFrom(this._newPosition);
  42068. var up = this.upVector;
  42069. if (this.allowUpsideDown && sinb < 0) {
  42070. up = up.clone();
  42071. up = up.negate();
  42072. }
  42073. if (this.getScene().useRightHandedSystem) {
  42074. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42075. }
  42076. else {
  42077. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42078. }
  42079. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42080. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42081. }
  42082. this._currentTarget = target;
  42083. return this._viewMatrix;
  42084. };
  42085. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42086. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42087. meshes = meshes || this.getScene().meshes;
  42088. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42089. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42090. this.radius = distance * this.zoomOnFactor;
  42091. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42092. };
  42093. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42094. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42095. var meshesOrMinMaxVector;
  42096. var distance;
  42097. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42098. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42099. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42100. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42101. }
  42102. else {
  42103. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42104. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42105. distance = minMaxVectorAndDistance.distance;
  42106. }
  42107. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42108. if (!doNotUpdateMaxZ) {
  42109. this.maxZ = distance * 2;
  42110. }
  42111. };
  42112. /**
  42113. * @override
  42114. * Override Camera.createRigCamera
  42115. */
  42116. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42117. var alphaShift = 0;
  42118. switch (this.cameraRigMode) {
  42119. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42120. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42121. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42122. case BABYLON.Camera.RIG_MODE_VR:
  42123. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42124. break;
  42125. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42126. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42127. break;
  42128. }
  42129. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42130. rigCam._cameraRigParams = {};
  42131. return rigCam;
  42132. };
  42133. /**
  42134. * @override
  42135. * Override Camera._updateRigCameras
  42136. */
  42137. ArcRotateCamera.prototype._updateRigCameras = function () {
  42138. var camLeft = this._rigCameras[0];
  42139. var camRight = this._rigCameras[1];
  42140. camLeft.beta = camRight.beta = this.beta;
  42141. camLeft.radius = camRight.radius = this.radius;
  42142. switch (this.cameraRigMode) {
  42143. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42144. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42145. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42146. case BABYLON.Camera.RIG_MODE_VR:
  42147. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42148. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42149. break;
  42150. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42151. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42152. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42153. break;
  42154. }
  42155. _super.prototype._updateRigCameras.call(this);
  42156. };
  42157. ArcRotateCamera.prototype.dispose = function () {
  42158. this.inputs.clear();
  42159. _super.prototype.dispose.call(this);
  42160. };
  42161. ArcRotateCamera.prototype.getClassName = function () {
  42162. return "ArcRotateCamera";
  42163. };
  42164. __decorate([
  42165. BABYLON.serialize()
  42166. ], ArcRotateCamera.prototype, "alpha", void 0);
  42167. __decorate([
  42168. BABYLON.serialize()
  42169. ], ArcRotateCamera.prototype, "beta", void 0);
  42170. __decorate([
  42171. BABYLON.serialize()
  42172. ], ArcRotateCamera.prototype, "radius", void 0);
  42173. __decorate([
  42174. BABYLON.serializeAsVector3("target")
  42175. ], ArcRotateCamera.prototype, "_target", void 0);
  42176. __decorate([
  42177. BABYLON.serialize()
  42178. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42179. __decorate([
  42180. BABYLON.serialize()
  42181. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42182. __decorate([
  42183. BABYLON.serialize()
  42184. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42185. __decorate([
  42186. BABYLON.serialize()
  42187. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42188. __decorate([
  42189. BABYLON.serialize()
  42190. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42191. __decorate([
  42192. BABYLON.serialize()
  42193. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42194. __decorate([
  42195. BABYLON.serialize()
  42196. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42197. __decorate([
  42198. BABYLON.serialize()
  42199. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42200. __decorate([
  42201. BABYLON.serialize()
  42202. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42203. __decorate([
  42204. BABYLON.serialize()
  42205. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42206. __decorate([
  42207. BABYLON.serialize()
  42208. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42209. __decorate([
  42210. BABYLON.serialize()
  42211. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42212. __decorate([
  42213. BABYLON.serialize()
  42214. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42215. __decorate([
  42216. BABYLON.serializeAsVector3()
  42217. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42218. __decorate([
  42219. BABYLON.serialize()
  42220. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42221. __decorate([
  42222. BABYLON.serialize()
  42223. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42224. __decorate([
  42225. BABYLON.serialize()
  42226. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42227. return ArcRotateCamera;
  42228. }(BABYLON.TargetCamera));
  42229. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42230. })(BABYLON || (BABYLON = {}));
  42231. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42232. var BABYLON;
  42233. (function (BABYLON) {
  42234. var HemisphericLight = /** @class */ (function (_super) {
  42235. __extends(HemisphericLight, _super);
  42236. /**
  42237. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42238. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42239. * The HemisphericLight can't cast shadows.
  42240. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42241. */
  42242. function HemisphericLight(name, direction, scene) {
  42243. var _this = _super.call(this, name, scene) || this;
  42244. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42245. _this.direction = direction || BABYLON.Vector3.Up();
  42246. return _this;
  42247. }
  42248. HemisphericLight.prototype._buildUniformLayout = function () {
  42249. this._uniformBuffer.addUniform("vLightData", 4);
  42250. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42251. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42252. this._uniformBuffer.addUniform("vLightGround", 3);
  42253. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42254. this._uniformBuffer.addUniform("depthValues", 2);
  42255. this._uniformBuffer.create();
  42256. };
  42257. /**
  42258. * Returns the string "HemisphericLight".
  42259. */
  42260. HemisphericLight.prototype.getClassName = function () {
  42261. return "HemisphericLight";
  42262. };
  42263. /**
  42264. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42265. * Returns the updated direction.
  42266. */
  42267. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42268. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42269. return this.direction;
  42270. };
  42271. HemisphericLight.prototype.getShadowGenerator = function () {
  42272. return null;
  42273. };
  42274. /**
  42275. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42276. * Returns the HemisphericLight.
  42277. */
  42278. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42279. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42280. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42281. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42282. return this;
  42283. };
  42284. HemisphericLight.prototype._getWorldMatrix = function () {
  42285. if (!this._worldMatrix) {
  42286. this._worldMatrix = BABYLON.Matrix.Identity();
  42287. }
  42288. return this._worldMatrix;
  42289. };
  42290. /**
  42291. * Returns the integer 3.
  42292. */
  42293. HemisphericLight.prototype.getTypeID = function () {
  42294. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42295. };
  42296. __decorate([
  42297. BABYLON.serializeAsColor3()
  42298. ], HemisphericLight.prototype, "groundColor", void 0);
  42299. __decorate([
  42300. BABYLON.serializeAsVector3()
  42301. ], HemisphericLight.prototype, "direction", void 0);
  42302. return HemisphericLight;
  42303. }(BABYLON.Light));
  42304. BABYLON.HemisphericLight = HemisphericLight;
  42305. })(BABYLON || (BABYLON = {}));
  42306. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42307. var BABYLON;
  42308. (function (BABYLON) {
  42309. var ShadowLight = /** @class */ (function (_super) {
  42310. __extends(ShadowLight, _super);
  42311. function ShadowLight() {
  42312. var _this = _super !== null && _super.apply(this, arguments) || this;
  42313. _this._needProjectionMatrixCompute = true;
  42314. return _this;
  42315. }
  42316. Object.defineProperty(ShadowLight.prototype, "direction", {
  42317. get: function () {
  42318. return this._direction;
  42319. },
  42320. set: function (value) {
  42321. this._direction = value;
  42322. },
  42323. enumerable: true,
  42324. configurable: true
  42325. });
  42326. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42327. get: function () {
  42328. return this._shadowMinZ;
  42329. },
  42330. set: function (value) {
  42331. this._shadowMinZ = value;
  42332. this.forceProjectionMatrixCompute();
  42333. },
  42334. enumerable: true,
  42335. configurable: true
  42336. });
  42337. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42338. get: function () {
  42339. return this._shadowMaxZ;
  42340. },
  42341. set: function (value) {
  42342. this._shadowMaxZ = value;
  42343. this.forceProjectionMatrixCompute();
  42344. },
  42345. enumerable: true,
  42346. configurable: true
  42347. });
  42348. /**
  42349. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  42350. */
  42351. ShadowLight.prototype.computeTransformedInformation = function () {
  42352. if (this.parent && this.parent.getWorldMatrix) {
  42353. if (!this.transformedPosition) {
  42354. this.transformedPosition = BABYLON.Vector3.Zero();
  42355. }
  42356. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42357. // In case the direction is present.
  42358. if (this.direction) {
  42359. if (!this.transformedDirection) {
  42360. this.transformedDirection = BABYLON.Vector3.Zero();
  42361. }
  42362. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42363. }
  42364. return true;
  42365. }
  42366. return false;
  42367. };
  42368. /**
  42369. * Return the depth scale used for the shadow map.
  42370. */
  42371. ShadowLight.prototype.getDepthScale = function () {
  42372. return 50.0;
  42373. };
  42374. /**
  42375. * Returns the light direction (Vector3) for any passed face index.
  42376. */
  42377. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42378. return this.transformedDirection ? this.transformedDirection : this.direction;
  42379. };
  42380. /**
  42381. * Returns the ShadowLight absolute position in the World.
  42382. */
  42383. ShadowLight.prototype.getAbsolutePosition = function () {
  42384. return this.transformedPosition ? this.transformedPosition : this.position;
  42385. };
  42386. /**
  42387. * Sets the ShadowLight direction toward the passed target (Vector3).
  42388. * Returns the updated ShadowLight direction (Vector3).
  42389. */
  42390. ShadowLight.prototype.setDirectionToTarget = function (target) {
  42391. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  42392. return this.direction;
  42393. };
  42394. /**
  42395. * Returns the light rotation (Vector3).
  42396. */
  42397. ShadowLight.prototype.getRotation = function () {
  42398. this.direction.normalize();
  42399. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  42400. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  42401. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  42402. };
  42403. /**
  42404. * Boolean : false by default.
  42405. */
  42406. ShadowLight.prototype.needCube = function () {
  42407. return false;
  42408. };
  42409. /**
  42410. * Specifies wether or not the projection matrix should be recomputed this frame.
  42411. */
  42412. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  42413. return this._needProjectionMatrixCompute;
  42414. };
  42415. /**
  42416. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  42417. */
  42418. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  42419. this._needProjectionMatrixCompute = true;
  42420. };
  42421. /**
  42422. * Get the world matrix of the sahdow lights.
  42423. */
  42424. ShadowLight.prototype._getWorldMatrix = function () {
  42425. if (!this._worldMatrix) {
  42426. this._worldMatrix = BABYLON.Matrix.Identity();
  42427. }
  42428. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42429. return this._worldMatrix;
  42430. };
  42431. /**
  42432. * Gets the minZ used for shadow according to both the scene and the light.
  42433. * @param activeCamera
  42434. */
  42435. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42436. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42437. };
  42438. /**
  42439. * Gets the maxZ used for shadow according to both the scene and the light.
  42440. * @param activeCamera
  42441. */
  42442. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42443. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42444. };
  42445. /**
  42446. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42447. * Returns the light.
  42448. */
  42449. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42450. if (this.customProjectionMatrixBuilder) {
  42451. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42452. }
  42453. else {
  42454. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42455. }
  42456. return this;
  42457. };
  42458. __decorate([
  42459. BABYLON.serializeAsVector3()
  42460. ], ShadowLight.prototype, "position", void 0);
  42461. __decorate([
  42462. BABYLON.serializeAsVector3()
  42463. ], ShadowLight.prototype, "direction", null);
  42464. __decorate([
  42465. BABYLON.serialize()
  42466. ], ShadowLight.prototype, "shadowMinZ", null);
  42467. __decorate([
  42468. BABYLON.serialize()
  42469. ], ShadowLight.prototype, "shadowMaxZ", null);
  42470. return ShadowLight;
  42471. }(BABYLON.Light));
  42472. BABYLON.ShadowLight = ShadowLight;
  42473. })(BABYLON || (BABYLON = {}));
  42474. //# sourceMappingURL=babylon.shadowLight.js.map
  42475. var BABYLON;
  42476. (function (BABYLON) {
  42477. var PointLight = /** @class */ (function (_super) {
  42478. __extends(PointLight, _super);
  42479. /**
  42480. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42481. * A PointLight emits the light in every direction.
  42482. * It can cast shadows.
  42483. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42484. * ```javascript
  42485. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42486. * ```
  42487. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42488. */
  42489. function PointLight(name, position, scene) {
  42490. var _this = _super.call(this, name, scene) || this;
  42491. _this._shadowAngle = Math.PI / 2;
  42492. _this.position = position;
  42493. return _this;
  42494. }
  42495. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42496. /**
  42497. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42498. * This specifies what angle the shadow will use to be created.
  42499. *
  42500. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42501. */
  42502. get: function () {
  42503. return this._shadowAngle;
  42504. },
  42505. /**
  42506. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42507. * This specifies what angle the shadow will use to be created.
  42508. *
  42509. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42510. */
  42511. set: function (value) {
  42512. this._shadowAngle = value;
  42513. this.forceProjectionMatrixCompute();
  42514. },
  42515. enumerable: true,
  42516. configurable: true
  42517. });
  42518. Object.defineProperty(PointLight.prototype, "direction", {
  42519. get: function () {
  42520. return this._direction;
  42521. },
  42522. /**
  42523. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42524. */
  42525. set: function (value) {
  42526. var previousNeedCube = this.needCube();
  42527. this._direction = value;
  42528. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42529. this._shadowGenerator.recreateShadowMap();
  42530. }
  42531. },
  42532. enumerable: true,
  42533. configurable: true
  42534. });
  42535. /**
  42536. * Returns the string "PointLight"
  42537. */
  42538. PointLight.prototype.getClassName = function () {
  42539. return "PointLight";
  42540. };
  42541. /**
  42542. * Returns the integer 0.
  42543. */
  42544. PointLight.prototype.getTypeID = function () {
  42545. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42546. };
  42547. /**
  42548. * Specifies wether or not the shadowmap should be a cube texture.
  42549. */
  42550. PointLight.prototype.needCube = function () {
  42551. return !this.direction;
  42552. };
  42553. /**
  42554. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42555. */
  42556. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42557. if (this.direction) {
  42558. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42559. }
  42560. else {
  42561. switch (faceIndex) {
  42562. case 0:
  42563. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42564. case 1:
  42565. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42566. case 2:
  42567. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42568. case 3:
  42569. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42570. case 4:
  42571. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42572. case 5:
  42573. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42574. }
  42575. }
  42576. return BABYLON.Vector3.Zero();
  42577. };
  42578. /**
  42579. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42580. * - fov = PI / 2
  42581. * - aspect ratio : 1.0
  42582. * - z-near and far equal to the active camera minZ and maxZ.
  42583. * Returns the PointLight.
  42584. */
  42585. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42586. var activeCamera = this.getScene().activeCamera;
  42587. if (!activeCamera) {
  42588. return;
  42589. }
  42590. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42591. };
  42592. PointLight.prototype._buildUniformLayout = function () {
  42593. this._uniformBuffer.addUniform("vLightData", 4);
  42594. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42595. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42596. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42597. this._uniformBuffer.addUniform("depthValues", 2);
  42598. this._uniformBuffer.create();
  42599. };
  42600. /**
  42601. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42602. * Returns the PointLight.
  42603. */
  42604. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42605. if (this.computeTransformedInformation()) {
  42606. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42607. return this;
  42608. }
  42609. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42610. return this;
  42611. };
  42612. __decorate([
  42613. BABYLON.serialize()
  42614. ], PointLight.prototype, "shadowAngle", null);
  42615. return PointLight;
  42616. }(BABYLON.ShadowLight));
  42617. BABYLON.PointLight = PointLight;
  42618. })(BABYLON || (BABYLON = {}));
  42619. //# sourceMappingURL=babylon.pointLight.js.map
  42620. var BABYLON;
  42621. (function (BABYLON) {
  42622. var DirectionalLight = /** @class */ (function (_super) {
  42623. __extends(DirectionalLight, _super);
  42624. /**
  42625. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42626. * The directional light is emitted from everywhere in the given direction.
  42627. * It can cast shawdows.
  42628. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42629. */
  42630. function DirectionalLight(name, direction, scene) {
  42631. var _this = _super.call(this, name, scene) || this;
  42632. _this._shadowFrustumSize = 0;
  42633. _this._shadowOrthoScale = 0.5;
  42634. _this.autoUpdateExtends = true;
  42635. // Cache
  42636. _this._orthoLeft = Number.MAX_VALUE;
  42637. _this._orthoRight = Number.MIN_VALUE;
  42638. _this._orthoTop = Number.MIN_VALUE;
  42639. _this._orthoBottom = Number.MAX_VALUE;
  42640. _this.position = direction.scale(-1.0);
  42641. _this.direction = direction;
  42642. return _this;
  42643. }
  42644. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42645. /**
  42646. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42647. */
  42648. get: function () {
  42649. return this._shadowFrustumSize;
  42650. },
  42651. /**
  42652. * Specifies a fix frustum size for the shadow generation.
  42653. */
  42654. set: function (value) {
  42655. this._shadowFrustumSize = value;
  42656. this.forceProjectionMatrixCompute();
  42657. },
  42658. enumerable: true,
  42659. configurable: true
  42660. });
  42661. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42662. get: function () {
  42663. return this._shadowOrthoScale;
  42664. },
  42665. set: function (value) {
  42666. this._shadowOrthoScale = value;
  42667. this.forceProjectionMatrixCompute();
  42668. },
  42669. enumerable: true,
  42670. configurable: true
  42671. });
  42672. /**
  42673. * Returns the string "DirectionalLight".
  42674. */
  42675. DirectionalLight.prototype.getClassName = function () {
  42676. return "DirectionalLight";
  42677. };
  42678. /**
  42679. * Returns the integer 1.
  42680. */
  42681. DirectionalLight.prototype.getTypeID = function () {
  42682. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42683. };
  42684. /**
  42685. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42686. * Returns the DirectionalLight Shadow projection matrix.
  42687. */
  42688. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42689. if (this.shadowFrustumSize > 0) {
  42690. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  42691. }
  42692. else {
  42693. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42694. }
  42695. };
  42696. /**
  42697. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  42698. * Returns the DirectionalLight Shadow projection matrix.
  42699. */
  42700. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  42701. var activeCamera = this.getScene().activeCamera;
  42702. if (!activeCamera) {
  42703. return;
  42704. }
  42705. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  42706. };
  42707. /**
  42708. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  42709. * Returns the DirectionalLight Shadow projection matrix.
  42710. */
  42711. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42712. var activeCamera = this.getScene().activeCamera;
  42713. if (!activeCamera) {
  42714. return;
  42715. }
  42716. // Check extends
  42717. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  42718. var tempVector3 = BABYLON.Vector3.Zero();
  42719. this._orthoLeft = Number.MAX_VALUE;
  42720. this._orthoRight = Number.MIN_VALUE;
  42721. this._orthoTop = Number.MIN_VALUE;
  42722. this._orthoBottom = Number.MAX_VALUE;
  42723. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  42724. var mesh = renderList[meshIndex];
  42725. if (!mesh) {
  42726. continue;
  42727. }
  42728. var boundingInfo = mesh.getBoundingInfo();
  42729. var boundingBox = boundingInfo.boundingBox;
  42730. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  42731. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  42732. if (tempVector3.x < this._orthoLeft)
  42733. this._orthoLeft = tempVector3.x;
  42734. if (tempVector3.y < this._orthoBottom)
  42735. this._orthoBottom = tempVector3.y;
  42736. if (tempVector3.x > this._orthoRight)
  42737. this._orthoRight = tempVector3.x;
  42738. if (tempVector3.y > this._orthoTop)
  42739. this._orthoTop = tempVector3.y;
  42740. }
  42741. }
  42742. }
  42743. var xOffset = this._orthoRight - this._orthoLeft;
  42744. var yOffset = this._orthoTop - this._orthoBottom;
  42745. 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);
  42746. };
  42747. DirectionalLight.prototype._buildUniformLayout = function () {
  42748. this._uniformBuffer.addUniform("vLightData", 4);
  42749. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42750. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42751. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42752. this._uniformBuffer.addUniform("depthValues", 2);
  42753. this._uniformBuffer.create();
  42754. };
  42755. /**
  42756. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  42757. * Returns the DirectionalLight.
  42758. */
  42759. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  42760. if (this.computeTransformedInformation()) {
  42761. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  42762. return this;
  42763. }
  42764. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  42765. return this;
  42766. };
  42767. /**
  42768. * Gets the minZ used for shadow according to both the scene and the light.
  42769. *
  42770. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42771. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42772. * @param activeCamera
  42773. */
  42774. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  42775. return 1;
  42776. };
  42777. /**
  42778. * Gets the maxZ used for shadow according to both the scene and the light.
  42779. *
  42780. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42781. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42782. * @param activeCamera
  42783. */
  42784. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  42785. return 1;
  42786. };
  42787. __decorate([
  42788. BABYLON.serialize()
  42789. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  42790. __decorate([
  42791. BABYLON.serialize()
  42792. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  42793. __decorate([
  42794. BABYLON.serialize()
  42795. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  42796. return DirectionalLight;
  42797. }(BABYLON.ShadowLight));
  42798. BABYLON.DirectionalLight = DirectionalLight;
  42799. })(BABYLON || (BABYLON = {}));
  42800. //# sourceMappingURL=babylon.directionalLight.js.map
  42801. var BABYLON;
  42802. (function (BABYLON) {
  42803. var SpotLight = /** @class */ (function (_super) {
  42804. __extends(SpotLight, _super);
  42805. /**
  42806. * Creates a SpotLight object in the scene with the passed parameters :
  42807. * - `position` (Vector3) is the initial SpotLight position,
  42808. * - `direction` (Vector3) is the initial SpotLight direction,
  42809. * - `angle` (float, in radians) is the spot light cone angle,
  42810. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  42811. * A spot light is a simply light oriented cone.
  42812. * It can cast shadows.
  42813. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42814. */
  42815. function SpotLight(name, position, direction, angle, exponent, scene) {
  42816. var _this = _super.call(this, name, scene) || this;
  42817. _this.position = position;
  42818. _this.direction = direction;
  42819. _this.angle = angle;
  42820. _this.exponent = exponent;
  42821. return _this;
  42822. }
  42823. Object.defineProperty(SpotLight.prototype, "angle", {
  42824. get: function () {
  42825. return this._angle;
  42826. },
  42827. set: function (value) {
  42828. this._angle = value;
  42829. this.forceProjectionMatrixCompute();
  42830. },
  42831. enumerable: true,
  42832. configurable: true
  42833. });
  42834. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  42835. get: function () {
  42836. return this._shadowAngleScale;
  42837. },
  42838. /**
  42839. * Allows scaling the angle of the light for shadow generation only.
  42840. */
  42841. set: function (value) {
  42842. this._shadowAngleScale = value;
  42843. this.forceProjectionMatrixCompute();
  42844. },
  42845. enumerable: true,
  42846. configurable: true
  42847. });
  42848. /**
  42849. * Returns the string "SpotLight".
  42850. */
  42851. SpotLight.prototype.getClassName = function () {
  42852. return "SpotLight";
  42853. };
  42854. /**
  42855. * Returns the integer 2.
  42856. */
  42857. SpotLight.prototype.getTypeID = function () {
  42858. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  42859. };
  42860. /**
  42861. * 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.
  42862. * Returns the SpotLight.
  42863. */
  42864. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42865. var activeCamera = this.getScene().activeCamera;
  42866. if (!activeCamera) {
  42867. return;
  42868. }
  42869. this._shadowAngleScale = this._shadowAngleScale || 1;
  42870. var angle = this._shadowAngleScale * this._angle;
  42871. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42872. };
  42873. SpotLight.prototype._buildUniformLayout = function () {
  42874. this._uniformBuffer.addUniform("vLightData", 4);
  42875. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42876. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42877. this._uniformBuffer.addUniform("vLightDirection", 3);
  42878. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42879. this._uniformBuffer.addUniform("depthValues", 2);
  42880. this._uniformBuffer.create();
  42881. };
  42882. /**
  42883. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  42884. * Return the SpotLight.
  42885. */
  42886. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  42887. var normalizeDirection;
  42888. if (this.computeTransformedInformation()) {
  42889. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  42890. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  42891. }
  42892. else {
  42893. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  42894. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42895. }
  42896. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  42897. return this;
  42898. };
  42899. __decorate([
  42900. BABYLON.serialize()
  42901. ], SpotLight.prototype, "angle", null);
  42902. __decorate([
  42903. BABYLON.serialize()
  42904. /**
  42905. * Allows scaling the angle of the light for shadow generation only.
  42906. */
  42907. ], SpotLight.prototype, "shadowAngleScale", null);
  42908. __decorate([
  42909. BABYLON.serialize()
  42910. ], SpotLight.prototype, "exponent", void 0);
  42911. return SpotLight;
  42912. }(BABYLON.ShadowLight));
  42913. BABYLON.SpotLight = SpotLight;
  42914. })(BABYLON || (BABYLON = {}));
  42915. //# sourceMappingURL=babylon.spotLight.js.map
  42916. var BABYLON;
  42917. (function (BABYLON) {
  42918. var AnimationRange = /** @class */ (function () {
  42919. function AnimationRange(name, from, to) {
  42920. this.name = name;
  42921. this.from = from;
  42922. this.to = to;
  42923. }
  42924. AnimationRange.prototype.clone = function () {
  42925. return new AnimationRange(this.name, this.from, this.to);
  42926. };
  42927. return AnimationRange;
  42928. }());
  42929. BABYLON.AnimationRange = AnimationRange;
  42930. /**
  42931. * Composed of a frame, and an action function
  42932. */
  42933. var AnimationEvent = /** @class */ (function () {
  42934. function AnimationEvent(frame, action, onlyOnce) {
  42935. this.frame = frame;
  42936. this.action = action;
  42937. this.onlyOnce = onlyOnce;
  42938. this.isDone = false;
  42939. }
  42940. return AnimationEvent;
  42941. }());
  42942. BABYLON.AnimationEvent = AnimationEvent;
  42943. var PathCursor = /** @class */ (function () {
  42944. function PathCursor(path) {
  42945. this.path = path;
  42946. this._onchange = new Array();
  42947. this.value = 0;
  42948. this.animations = new Array();
  42949. }
  42950. PathCursor.prototype.getPoint = function () {
  42951. var point = this.path.getPointAtLengthPosition(this.value);
  42952. return new BABYLON.Vector3(point.x, 0, point.y);
  42953. };
  42954. PathCursor.prototype.moveAhead = function (step) {
  42955. if (step === void 0) { step = 0.002; }
  42956. this.move(step);
  42957. return this;
  42958. };
  42959. PathCursor.prototype.moveBack = function (step) {
  42960. if (step === void 0) { step = 0.002; }
  42961. this.move(-step);
  42962. return this;
  42963. };
  42964. PathCursor.prototype.move = function (step) {
  42965. if (Math.abs(step) > 1) {
  42966. throw "step size should be less than 1.";
  42967. }
  42968. this.value += step;
  42969. this.ensureLimits();
  42970. this.raiseOnChange();
  42971. return this;
  42972. };
  42973. PathCursor.prototype.ensureLimits = function () {
  42974. while (this.value > 1) {
  42975. this.value -= 1;
  42976. }
  42977. while (this.value < 0) {
  42978. this.value += 1;
  42979. }
  42980. return this;
  42981. };
  42982. // used by animation engine
  42983. PathCursor.prototype.raiseOnChange = function () {
  42984. var _this = this;
  42985. this._onchange.forEach(function (f) { return f(_this); });
  42986. return this;
  42987. };
  42988. PathCursor.prototype.onchange = function (f) {
  42989. this._onchange.push(f);
  42990. return this;
  42991. };
  42992. return PathCursor;
  42993. }());
  42994. BABYLON.PathCursor = PathCursor;
  42995. var AnimationKeyInterpolation;
  42996. (function (AnimationKeyInterpolation) {
  42997. /**
  42998. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  42999. */
  43000. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43001. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43002. var Animation = /** @class */ (function () {
  43003. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43004. this.name = name;
  43005. this.targetProperty = targetProperty;
  43006. this.framePerSecond = framePerSecond;
  43007. this.dataType = dataType;
  43008. this.loopMode = loopMode;
  43009. this.enableBlending = enableBlending;
  43010. this._runtimeAnimations = new Array();
  43011. // The set of event that will be linked to this animation
  43012. this._events = new Array();
  43013. this.blendingSpeed = 0.01;
  43014. this._ranges = {};
  43015. this.targetPropertyPath = targetProperty.split(".");
  43016. this.dataType = dataType;
  43017. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43018. }
  43019. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43020. var dataType = undefined;
  43021. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43022. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43023. }
  43024. else if (from instanceof BABYLON.Quaternion) {
  43025. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43026. }
  43027. else if (from instanceof BABYLON.Vector3) {
  43028. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43029. }
  43030. else if (from instanceof BABYLON.Vector2) {
  43031. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43032. }
  43033. else if (from instanceof BABYLON.Color3) {
  43034. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43035. }
  43036. else if (from instanceof BABYLON.Size) {
  43037. dataType = Animation.ANIMATIONTYPE_SIZE;
  43038. }
  43039. if (dataType == undefined) {
  43040. return null;
  43041. }
  43042. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43043. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43044. animation.setKeys(keys);
  43045. if (easingFunction !== undefined) {
  43046. animation.setEasingFunction(easingFunction);
  43047. }
  43048. return animation;
  43049. };
  43050. /**
  43051. * Sets up an animation.
  43052. * @param property the property to animate
  43053. * @param animationType the animation type to apply
  43054. * @param easingFunction the easing function used in the animation
  43055. * @returns The created animation
  43056. */
  43057. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43058. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43059. animation.setEasingFunction(easingFunction);
  43060. return animation;
  43061. };
  43062. /**
  43063. * Create and start an animation on a node
  43064. * @param {string} name defines the name of the global animation that will be run on all nodes
  43065. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43066. * @param {string} targetProperty defines property to animate
  43067. * @param {number} framePerSecond defines the number of frame per second yo use
  43068. * @param {number} totalFrame defines the number of frames in total
  43069. * @param {any} from defines the initial value
  43070. * @param {any} to defines the final value
  43071. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43072. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43073. * @param onAnimationEnd defines the callback to call when animation end
  43074. * @returns the animatable created for this animation
  43075. */
  43076. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43077. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43078. if (!animation) {
  43079. return null;
  43080. }
  43081. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43082. };
  43083. /**
  43084. * Create and start an animation on a node and its descendants
  43085. * @param {string} name defines the name of the global animation that will be run on all nodes
  43086. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43087. * @param {boolean} 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.
  43088. * @param {string} targetProperty defines property to animate
  43089. * @param {number} framePerSecond defines the number of frame per second yo use
  43090. * @param {number} totalFrame defines the number of frames in total
  43091. * @param {any} from defines the initial value
  43092. * @param {any} to defines the final value
  43093. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43094. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43095. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43096. * @returns the list of animatables created for all nodes
  43097. * @example https://www.babylonjs-playground.com/#MH0VLI
  43098. */
  43099. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43100. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43101. if (!animation) {
  43102. return null;
  43103. }
  43104. var scene = node.getScene();
  43105. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43106. };
  43107. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43108. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43109. if (!animation) {
  43110. return null;
  43111. }
  43112. node.animations.push(animation);
  43113. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43114. };
  43115. /**
  43116. * Transition property of the Camera to the target Value.
  43117. * @param property The property to transition
  43118. * @param targetValue The target Value of the property
  43119. * @param host The object where the property to animate belongs
  43120. * @param scene Scene used to run the animation
  43121. * @param frameRate Framerate (in frame/s) to use
  43122. * @param transition The transition type we want to use
  43123. * @param duration The duration of the animation, in milliseconds
  43124. * @param onAnimationEnd Call back trigger at the end of the animation.
  43125. */
  43126. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43127. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43128. if (duration <= 0) {
  43129. host[property] = targetValue;
  43130. if (onAnimationEnd) {
  43131. onAnimationEnd();
  43132. }
  43133. return null;
  43134. }
  43135. var endFrame = frameRate * (duration / 1000);
  43136. transition.setKeys([{
  43137. frame: 0,
  43138. value: host[property].clone ? host[property].clone() : host[property]
  43139. },
  43140. {
  43141. frame: endFrame,
  43142. value: targetValue
  43143. }]);
  43144. if (!host.animations) {
  43145. host.animations = [];
  43146. }
  43147. host.animations.push(transition);
  43148. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43149. animation.onAnimationEnd = onAnimationEnd;
  43150. return animation;
  43151. };
  43152. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43153. /**
  43154. * Return the array of runtime animations currently using this animation
  43155. */
  43156. get: function () {
  43157. return this._runtimeAnimations;
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43163. get: function () {
  43164. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43165. var runtimeAnimation = _a[_i];
  43166. if (!runtimeAnimation.isStopped) {
  43167. return true;
  43168. }
  43169. }
  43170. return false;
  43171. },
  43172. enumerable: true,
  43173. configurable: true
  43174. });
  43175. // Methods
  43176. /**
  43177. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43178. */
  43179. Animation.prototype.toString = function (fullDetails) {
  43180. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43181. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43182. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43183. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  43184. if (fullDetails) {
  43185. ret += ", Ranges: {";
  43186. var first = true;
  43187. for (var name in this._ranges) {
  43188. if (first) {
  43189. ret += ", ";
  43190. first = false;
  43191. }
  43192. ret += name;
  43193. }
  43194. ret += "}";
  43195. }
  43196. return ret;
  43197. };
  43198. /**
  43199. * Add an event to this animation.
  43200. */
  43201. Animation.prototype.addEvent = function (event) {
  43202. this._events.push(event);
  43203. };
  43204. /**
  43205. * Remove all events found at the given frame
  43206. * @param frame
  43207. */
  43208. Animation.prototype.removeEvents = function (frame) {
  43209. for (var index = 0; index < this._events.length; index++) {
  43210. if (this._events[index].frame === frame) {
  43211. this._events.splice(index, 1);
  43212. index--;
  43213. }
  43214. }
  43215. };
  43216. Animation.prototype.getEvents = function () {
  43217. return this._events;
  43218. };
  43219. Animation.prototype.createRange = function (name, from, to) {
  43220. // check name not already in use; could happen for bones after serialized
  43221. if (!this._ranges[name]) {
  43222. this._ranges[name] = new AnimationRange(name, from, to);
  43223. }
  43224. };
  43225. Animation.prototype.deleteRange = function (name, deleteFrames) {
  43226. if (deleteFrames === void 0) { deleteFrames = true; }
  43227. var range = this._ranges[name];
  43228. if (!range) {
  43229. return;
  43230. }
  43231. if (deleteFrames) {
  43232. var from = range.from;
  43233. var to = range.to;
  43234. // this loop MUST go high to low for multiple splices to work
  43235. for (var key = this._keys.length - 1; key >= 0; key--) {
  43236. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  43237. this._keys.splice(key, 1);
  43238. }
  43239. }
  43240. }
  43241. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  43242. };
  43243. Animation.prototype.getRange = function (name) {
  43244. return this._ranges[name];
  43245. };
  43246. Animation.prototype.getKeys = function () {
  43247. return this._keys;
  43248. };
  43249. Animation.prototype.getHighestFrame = function () {
  43250. var ret = 0;
  43251. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  43252. if (ret < this._keys[key].frame) {
  43253. ret = this._keys[key].frame;
  43254. }
  43255. }
  43256. return ret;
  43257. };
  43258. Animation.prototype.getEasingFunction = function () {
  43259. return this._easingFunction;
  43260. };
  43261. Animation.prototype.setEasingFunction = function (easingFunction) {
  43262. this._easingFunction = easingFunction;
  43263. };
  43264. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  43265. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  43266. };
  43267. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43268. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43269. };
  43270. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  43271. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  43272. };
  43273. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43274. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  43275. };
  43276. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  43277. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  43278. };
  43279. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43280. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43281. };
  43282. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  43283. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  43284. };
  43285. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43286. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43287. };
  43288. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  43289. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  43290. };
  43291. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  43292. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  43293. };
  43294. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  43295. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  43296. };
  43297. Animation.prototype.clone = function () {
  43298. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  43299. clone.enableBlending = this.enableBlending;
  43300. clone.blendingSpeed = this.blendingSpeed;
  43301. if (this._keys) {
  43302. clone.setKeys(this._keys);
  43303. }
  43304. if (this._ranges) {
  43305. clone._ranges = {};
  43306. for (var name in this._ranges) {
  43307. var range = this._ranges[name];
  43308. if (!range) {
  43309. continue;
  43310. }
  43311. clone._ranges[name] = range.clone();
  43312. }
  43313. }
  43314. return clone;
  43315. };
  43316. Animation.prototype.setKeys = function (values) {
  43317. this._keys = values.slice(0);
  43318. };
  43319. Animation.prototype.serialize = function () {
  43320. var serializationObject = {};
  43321. serializationObject.name = this.name;
  43322. serializationObject.property = this.targetProperty;
  43323. serializationObject.framePerSecond = this.framePerSecond;
  43324. serializationObject.dataType = this.dataType;
  43325. serializationObject.loopBehavior = this.loopMode;
  43326. serializationObject.enableBlending = this.enableBlending;
  43327. serializationObject.blendingSpeed = this.blendingSpeed;
  43328. var dataType = this.dataType;
  43329. serializationObject.keys = [];
  43330. var keys = this.getKeys();
  43331. for (var index = 0; index < keys.length; index++) {
  43332. var animationKey = keys[index];
  43333. var key = {};
  43334. key.frame = animationKey.frame;
  43335. switch (dataType) {
  43336. case Animation.ANIMATIONTYPE_FLOAT:
  43337. key.values = [animationKey.value];
  43338. break;
  43339. case Animation.ANIMATIONTYPE_QUATERNION:
  43340. case Animation.ANIMATIONTYPE_MATRIX:
  43341. case Animation.ANIMATIONTYPE_VECTOR3:
  43342. case Animation.ANIMATIONTYPE_COLOR3:
  43343. key.values = animationKey.value.asArray();
  43344. break;
  43345. }
  43346. serializationObject.keys.push(key);
  43347. }
  43348. serializationObject.ranges = [];
  43349. for (var name in this._ranges) {
  43350. var source = this._ranges[name];
  43351. if (!source) {
  43352. continue;
  43353. }
  43354. var range = {};
  43355. range.name = name;
  43356. range.from = source.from;
  43357. range.to = source.to;
  43358. serializationObject.ranges.push(range);
  43359. }
  43360. return serializationObject;
  43361. };
  43362. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  43363. get: function () {
  43364. return Animation._ANIMATIONTYPE_FLOAT;
  43365. },
  43366. enumerable: true,
  43367. configurable: true
  43368. });
  43369. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  43370. get: function () {
  43371. return Animation._ANIMATIONTYPE_VECTOR3;
  43372. },
  43373. enumerable: true,
  43374. configurable: true
  43375. });
  43376. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  43377. get: function () {
  43378. return Animation._ANIMATIONTYPE_VECTOR2;
  43379. },
  43380. enumerable: true,
  43381. configurable: true
  43382. });
  43383. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  43384. get: function () {
  43385. return Animation._ANIMATIONTYPE_SIZE;
  43386. },
  43387. enumerable: true,
  43388. configurable: true
  43389. });
  43390. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  43391. get: function () {
  43392. return Animation._ANIMATIONTYPE_QUATERNION;
  43393. },
  43394. enumerable: true,
  43395. configurable: true
  43396. });
  43397. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  43398. get: function () {
  43399. return Animation._ANIMATIONTYPE_MATRIX;
  43400. },
  43401. enumerable: true,
  43402. configurable: true
  43403. });
  43404. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  43405. get: function () {
  43406. return Animation._ANIMATIONTYPE_COLOR3;
  43407. },
  43408. enumerable: true,
  43409. configurable: true
  43410. });
  43411. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  43412. get: function () {
  43413. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  43414. },
  43415. enumerable: true,
  43416. configurable: true
  43417. });
  43418. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  43419. get: function () {
  43420. return Animation._ANIMATIONLOOPMODE_CYCLE;
  43421. },
  43422. enumerable: true,
  43423. configurable: true
  43424. });
  43425. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  43426. get: function () {
  43427. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43428. },
  43429. enumerable: true,
  43430. configurable: true
  43431. });
  43432. Animation.Parse = function (parsedAnimation) {
  43433. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43434. var dataType = parsedAnimation.dataType;
  43435. var keys = [];
  43436. var data;
  43437. var index;
  43438. if (parsedAnimation.enableBlending) {
  43439. animation.enableBlending = parsedAnimation.enableBlending;
  43440. }
  43441. if (parsedAnimation.blendingSpeed) {
  43442. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43443. }
  43444. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43445. var key = parsedAnimation.keys[index];
  43446. var inTangent;
  43447. var outTangent;
  43448. switch (dataType) {
  43449. case Animation.ANIMATIONTYPE_FLOAT:
  43450. data = key.values[0];
  43451. if (key.values.length >= 1) {
  43452. inTangent = key.values[1];
  43453. }
  43454. if (key.values.length >= 2) {
  43455. outTangent = key.values[2];
  43456. }
  43457. break;
  43458. case Animation.ANIMATIONTYPE_QUATERNION:
  43459. data = BABYLON.Quaternion.FromArray(key.values);
  43460. if (key.values.length >= 8) {
  43461. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43462. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43463. inTangent = _inTangent;
  43464. }
  43465. }
  43466. if (key.values.length >= 12) {
  43467. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43468. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43469. outTangent = _outTangent;
  43470. }
  43471. }
  43472. break;
  43473. case Animation.ANIMATIONTYPE_MATRIX:
  43474. data = BABYLON.Matrix.FromArray(key.values);
  43475. break;
  43476. case Animation.ANIMATIONTYPE_COLOR3:
  43477. data = BABYLON.Color3.FromArray(key.values);
  43478. break;
  43479. case Animation.ANIMATIONTYPE_VECTOR3:
  43480. default:
  43481. data = BABYLON.Vector3.FromArray(key.values);
  43482. break;
  43483. }
  43484. var keyData = {};
  43485. keyData.frame = key.frame;
  43486. keyData.value = data;
  43487. if (inTangent != undefined) {
  43488. keyData.inTangent = inTangent;
  43489. }
  43490. if (outTangent != undefined) {
  43491. keyData.outTangent = outTangent;
  43492. }
  43493. keys.push(keyData);
  43494. }
  43495. animation.setKeys(keys);
  43496. if (parsedAnimation.ranges) {
  43497. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43498. data = parsedAnimation.ranges[index];
  43499. animation.createRange(data.name, data.from, data.to);
  43500. }
  43501. }
  43502. return animation;
  43503. };
  43504. Animation.AppendSerializedAnimations = function (source, destination) {
  43505. if (source.animations) {
  43506. destination.animations = [];
  43507. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43508. var animation = source.animations[animationIndex];
  43509. destination.animations.push(animation.serialize());
  43510. }
  43511. }
  43512. };
  43513. Animation.AllowMatricesInterpolation = false;
  43514. // Statics
  43515. Animation._ANIMATIONTYPE_FLOAT = 0;
  43516. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43517. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43518. Animation._ANIMATIONTYPE_MATRIX = 3;
  43519. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43520. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43521. Animation._ANIMATIONTYPE_SIZE = 6;
  43522. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43523. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43524. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43525. return Animation;
  43526. }());
  43527. BABYLON.Animation = Animation;
  43528. })(BABYLON || (BABYLON = {}));
  43529. //# sourceMappingURL=babylon.animation.js.map
  43530. var BABYLON;
  43531. (function (BABYLON) {
  43532. /**
  43533. * This class defines the direct association between an animation and a target
  43534. */
  43535. var TargetedAnimation = /** @class */ (function () {
  43536. function TargetedAnimation() {
  43537. }
  43538. return TargetedAnimation;
  43539. }());
  43540. BABYLON.TargetedAnimation = TargetedAnimation;
  43541. /**
  43542. * Use this class to create coordinated animations on multiple targets
  43543. */
  43544. var AnimationGroup = /** @class */ (function () {
  43545. function AnimationGroup(name, scene) {
  43546. if (scene === void 0) { scene = null; }
  43547. this.name = name;
  43548. this._targetedAnimations = new Array();
  43549. this._animatables = new Array();
  43550. this._from = Number.MAX_VALUE;
  43551. this._to = -Number.MAX_VALUE;
  43552. this._speedRatio = 1;
  43553. this.onAnimationEndObservable = new BABYLON.Observable();
  43554. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43555. this._scene.animationGroups.push(this);
  43556. }
  43557. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43558. /**
  43559. * Define if the animations are started
  43560. */
  43561. get: function () {
  43562. return this._isStarted;
  43563. },
  43564. enumerable: true,
  43565. configurable: true
  43566. });
  43567. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43568. /**
  43569. * Gets or sets the speed ratio to use for all animations
  43570. */
  43571. get: function () {
  43572. return this._speedRatio;
  43573. },
  43574. /**
  43575. * Gets or sets the speed ratio to use for all animations
  43576. */
  43577. set: function (value) {
  43578. if (this._speedRatio === value) {
  43579. return;
  43580. }
  43581. this._speedRatio = value;
  43582. for (var index = 0; index < this._animatables.length; index++) {
  43583. var animatable = this._animatables[index];
  43584. animatable.speedRatio = this._speedRatio;
  43585. }
  43586. },
  43587. enumerable: true,
  43588. configurable: true
  43589. });
  43590. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43591. /**
  43592. * Gets the targeted animations for this animation group
  43593. */
  43594. get: function () {
  43595. return this._targetedAnimations;
  43596. },
  43597. enumerable: true,
  43598. configurable: true
  43599. });
  43600. /**
  43601. * Add an animation (with its target) in the group
  43602. * @param animation defines the animation we want to add
  43603. * @param target defines the target of the animation
  43604. * @returns the {BABYLON.TargetedAnimation} object
  43605. */
  43606. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43607. var targetedAnimation = {
  43608. animation: animation,
  43609. target: target
  43610. };
  43611. var keys = animation.getKeys();
  43612. if (this._from > keys[0].frame) {
  43613. this._from = keys[0].frame;
  43614. }
  43615. if (this._to < keys[keys.length - 1].frame) {
  43616. this._to = keys[keys.length - 1].frame;
  43617. }
  43618. this._targetedAnimations.push(targetedAnimation);
  43619. return targetedAnimation;
  43620. };
  43621. /**
  43622. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43623. * It can add constant keys at begin or end
  43624. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43625. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43626. */
  43627. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43628. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43629. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43630. beginFrame = Math.max(beginFrame, this._from);
  43631. endFrame = Math.min(endFrame, this._to);
  43632. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43633. var targetedAnimation = this._targetedAnimations[index];
  43634. var keys = targetedAnimation.animation.getKeys();
  43635. var startKey = keys[0];
  43636. var endKey = keys[keys.length - 1];
  43637. if (startKey.frame > beginFrame) {
  43638. var newKey = {
  43639. frame: beginFrame,
  43640. value: startKey.value,
  43641. inTangent: startKey.inTangent,
  43642. outTangent: startKey.outTangent,
  43643. interpolation: startKey.interpolation
  43644. };
  43645. keys.splice(0, 0, newKey);
  43646. }
  43647. if (endKey.frame < endFrame) {
  43648. var newKey = {
  43649. frame: endFrame,
  43650. value: endKey.value,
  43651. inTangent: endKey.outTangent,
  43652. outTangent: endKey.outTangent,
  43653. interpolation: endKey.interpolation
  43654. };
  43655. keys.push(newKey);
  43656. }
  43657. }
  43658. return this;
  43659. };
  43660. /**
  43661. * Start all animations on given targets
  43662. * @param loop defines if animations must loop
  43663. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43664. */
  43665. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43666. var _this = this;
  43667. if (loop === void 0) { loop = false; }
  43668. if (speedRatio === void 0) { speedRatio = 1; }
  43669. if (this._isStarted || this._targetedAnimations.length === 0) {
  43670. return this;
  43671. }
  43672. var _loop_1 = function () {
  43673. var targetedAnimation = this_1._targetedAnimations[index];
  43674. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43675. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43676. }));
  43677. };
  43678. var this_1 = this;
  43679. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43680. _loop_1();
  43681. }
  43682. this._speedRatio = speedRatio;
  43683. this._isStarted = true;
  43684. return this;
  43685. };
  43686. /**
  43687. * Pause all animations
  43688. */
  43689. AnimationGroup.prototype.pause = function () {
  43690. if (!this._isStarted) {
  43691. return this;
  43692. }
  43693. for (var index = 0; index < this._animatables.length; index++) {
  43694. var animatable = this._animatables[index];
  43695. animatable.pause();
  43696. }
  43697. return this;
  43698. };
  43699. /**
  43700. * Play all animations to initial state
  43701. * This function will start() the animations if they were not started or will restart() them if they were paused
  43702. * @param loop defines if animations must loop
  43703. */
  43704. AnimationGroup.prototype.play = function (loop) {
  43705. if (this.isStarted) {
  43706. if (loop !== undefined) {
  43707. for (var index = 0; index < this._animatables.length; index++) {
  43708. var animatable = this._animatables[index];
  43709. animatable.loopAnimation = loop;
  43710. }
  43711. }
  43712. this.restart();
  43713. }
  43714. else {
  43715. this.start(loop, this._speedRatio);
  43716. }
  43717. return this;
  43718. };
  43719. /**
  43720. * Reset all animations to initial state
  43721. */
  43722. AnimationGroup.prototype.reset = function () {
  43723. if (!this._isStarted) {
  43724. return this;
  43725. }
  43726. for (var index = 0; index < this._animatables.length; index++) {
  43727. var animatable = this._animatables[index];
  43728. animatable.reset();
  43729. }
  43730. return this;
  43731. };
  43732. /**
  43733. * Restart animations from key 0
  43734. */
  43735. AnimationGroup.prototype.restart = function () {
  43736. if (!this._isStarted) {
  43737. return this;
  43738. }
  43739. for (var index = 0; index < this._animatables.length; index++) {
  43740. var animatable = this._animatables[index];
  43741. animatable.restart();
  43742. }
  43743. return this;
  43744. };
  43745. /**
  43746. * Stop all animations
  43747. */
  43748. AnimationGroup.prototype.stop = function () {
  43749. if (!this._isStarted) {
  43750. return this;
  43751. }
  43752. for (var index = 0; index < this._animatables.length; index++) {
  43753. var animatable = this._animatables[index];
  43754. animatable.stop();
  43755. }
  43756. this._isStarted = false;
  43757. return this;
  43758. };
  43759. /**
  43760. * Dispose all associated resources
  43761. */
  43762. AnimationGroup.prototype.dispose = function () {
  43763. this._targetedAnimations = [];
  43764. this._animatables = [];
  43765. var index = this._scene.animationGroups.indexOf(this);
  43766. if (index > -1) {
  43767. this._scene.animationGroups.splice(index, 1);
  43768. }
  43769. };
  43770. return AnimationGroup;
  43771. }());
  43772. BABYLON.AnimationGroup = AnimationGroup;
  43773. })(BABYLON || (BABYLON = {}));
  43774. //# sourceMappingURL=babylon.animationGroup.js.map
  43775. var BABYLON;
  43776. (function (BABYLON) {
  43777. var RuntimeAnimation = /** @class */ (function () {
  43778. function RuntimeAnimation(target, animation) {
  43779. this._offsetsCache = {};
  43780. this._highLimitsCache = {};
  43781. this._stopped = false;
  43782. this._blendingFactor = 0;
  43783. this._ratioOffset = 0;
  43784. this._animation = animation;
  43785. this._target = target;
  43786. animation._runtimeAnimations.push(this);
  43787. }
  43788. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  43789. get: function () {
  43790. return this._animation;
  43791. },
  43792. enumerable: true,
  43793. configurable: true
  43794. });
  43795. RuntimeAnimation.prototype.reset = function () {
  43796. this._offsetsCache = {};
  43797. this._highLimitsCache = {};
  43798. this.currentFrame = 0;
  43799. this._blendingFactor = 0;
  43800. this._originalBlendValue = null;
  43801. };
  43802. RuntimeAnimation.prototype.isStopped = function () {
  43803. return this._stopped;
  43804. };
  43805. RuntimeAnimation.prototype.dispose = function () {
  43806. var index = this._animation.runtimeAnimations.indexOf(this);
  43807. if (index > -1) {
  43808. this._animation.runtimeAnimations.splice(index, 1);
  43809. }
  43810. };
  43811. RuntimeAnimation.prototype._getKeyValue = function (value) {
  43812. if (typeof value === "function") {
  43813. return value();
  43814. }
  43815. return value;
  43816. };
  43817. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  43818. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  43819. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  43820. }
  43821. this.currentFrame = currentFrame;
  43822. var keys = this._animation.getKeys();
  43823. // Try to get a hash to find the right key
  43824. 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));
  43825. if (keys[startKeyIndex].frame >= currentFrame) {
  43826. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  43827. startKeyIndex--;
  43828. }
  43829. }
  43830. for (var key = startKeyIndex; key < keys.length; key++) {
  43831. var endKey = keys[key + 1];
  43832. if (endKey.frame >= currentFrame) {
  43833. var startKey = keys[key];
  43834. var startValue = this._getKeyValue(startKey.value);
  43835. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  43836. return startValue;
  43837. }
  43838. var endValue = this._getKeyValue(endKey.value);
  43839. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  43840. var frameDelta = endKey.frame - startKey.frame;
  43841. // gradient : percent of currentFrame between the frame inf and the frame sup
  43842. var gradient = (currentFrame - startKey.frame) / frameDelta;
  43843. // check for easingFunction and correction of gradient
  43844. var easingFunction = this._animation.getEasingFunction();
  43845. if (easingFunction != null) {
  43846. gradient = easingFunction.ease(gradient);
  43847. }
  43848. switch (this._animation.dataType) {
  43849. // Float
  43850. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43851. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  43852. switch (loopMode) {
  43853. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43854. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43855. return floatValue;
  43856. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43857. return offsetValue * repeatCount + floatValue;
  43858. }
  43859. break;
  43860. // Quaternion
  43861. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43862. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  43863. switch (loopMode) {
  43864. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43865. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43866. return quatValue;
  43867. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43868. return quatValue.add(offsetValue.scale(repeatCount));
  43869. }
  43870. return quatValue;
  43871. // Vector3
  43872. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43873. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  43874. switch (loopMode) {
  43875. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43876. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43877. return vec3Value;
  43878. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43879. return vec3Value.add(offsetValue.scale(repeatCount));
  43880. }
  43881. // Vector2
  43882. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43883. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  43884. switch (loopMode) {
  43885. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43886. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43887. return vec2Value;
  43888. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43889. return vec2Value.add(offsetValue.scale(repeatCount));
  43890. }
  43891. // Size
  43892. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43893. switch (loopMode) {
  43894. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43895. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43896. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  43897. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43898. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43899. }
  43900. // Color3
  43901. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43902. switch (loopMode) {
  43903. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43904. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43905. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  43906. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43907. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43908. }
  43909. // Matrix
  43910. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  43911. switch (loopMode) {
  43912. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43913. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43914. if (BABYLON.Animation.AllowMatricesInterpolation) {
  43915. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  43916. }
  43917. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43918. return startValue;
  43919. }
  43920. default:
  43921. break;
  43922. }
  43923. break;
  43924. }
  43925. }
  43926. return this._getKeyValue(keys[keys.length - 1].value);
  43927. };
  43928. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  43929. if (blend === void 0) { blend = false; }
  43930. // Set value
  43931. var path;
  43932. var destination;
  43933. var targetPropertyPath = this._animation.targetPropertyPath;
  43934. if (targetPropertyPath.length > 1) {
  43935. var property = this._target[targetPropertyPath[0]];
  43936. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  43937. property = property[targetPropertyPath[index]];
  43938. }
  43939. path = targetPropertyPath[targetPropertyPath.length - 1];
  43940. destination = property;
  43941. }
  43942. else {
  43943. path = targetPropertyPath[0];
  43944. destination = this._target;
  43945. }
  43946. // Blending
  43947. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  43948. if (!this._originalBlendValue) {
  43949. if (destination[path].clone) {
  43950. this._originalBlendValue = destination[path].clone();
  43951. }
  43952. else {
  43953. this._originalBlendValue = destination[path];
  43954. }
  43955. }
  43956. if (this._originalBlendValue.prototype) {
  43957. if (this._originalBlendValue.prototype.Lerp) {
  43958. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  43959. }
  43960. else {
  43961. destination[path] = currentValue;
  43962. }
  43963. }
  43964. else if (this._originalBlendValue.m) {
  43965. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  43966. }
  43967. else {
  43968. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  43969. }
  43970. this._blendingFactor += this._animation.blendingSpeed;
  43971. }
  43972. else {
  43973. destination[path] = currentValue;
  43974. }
  43975. if (this._target.markAsDirty) {
  43976. this._target.markAsDirty(this._animation.targetProperty);
  43977. }
  43978. };
  43979. RuntimeAnimation.prototype.goToFrame = function (frame) {
  43980. var keys = this._animation.getKeys();
  43981. if (frame < keys[0].frame) {
  43982. frame = keys[0].frame;
  43983. }
  43984. else if (frame > keys[keys.length - 1].frame) {
  43985. frame = keys[keys.length - 1].frame;
  43986. }
  43987. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  43988. this.setValue(currentValue);
  43989. };
  43990. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  43991. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  43992. this._ratioOffset = this._previousRatio - newRatio;
  43993. };
  43994. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  43995. if (blend === void 0) { blend = false; }
  43996. var targetPropertyPath = this._animation.targetPropertyPath;
  43997. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  43998. this._stopped = true;
  43999. return false;
  44000. }
  44001. var returnValue = true;
  44002. var keys = this._animation.getKeys();
  44003. // Adding a start key at frame 0 if missing
  44004. if (keys[0].frame !== 0) {
  44005. var newKey = { frame: 0, value: keys[0].value };
  44006. keys.splice(0, 0, newKey);
  44007. }
  44008. // Check limits
  44009. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44010. from = keys[0].frame;
  44011. }
  44012. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44013. to = keys[keys.length - 1].frame;
  44014. }
  44015. //to and from cannot be the same key
  44016. if (from === to) {
  44017. if (from > keys[0].frame) {
  44018. from--;
  44019. }
  44020. else if (to < keys[keys.length - 1].frame) {
  44021. to++;
  44022. }
  44023. }
  44024. // Compute ratio
  44025. var range = to - from;
  44026. var offsetValue;
  44027. // ratio represents the frame delta between from and to
  44028. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44029. var highLimitValue = 0;
  44030. this._previousDelay = delay;
  44031. this._previousRatio = ratio;
  44032. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44033. returnValue = false;
  44034. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44035. }
  44036. else {
  44037. // Get max value if required
  44038. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44039. var keyOffset = to.toString() + from.toString();
  44040. if (!this._offsetsCache[keyOffset]) {
  44041. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44042. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44043. switch (this._animation.dataType) {
  44044. // Float
  44045. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44046. this._offsetsCache[keyOffset] = toValue - fromValue;
  44047. break;
  44048. // Quaternion
  44049. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44050. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44051. break;
  44052. // Vector3
  44053. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44054. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44055. // Vector2
  44056. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44057. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44058. // Size
  44059. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44060. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44061. // Color3
  44062. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44063. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44064. default:
  44065. break;
  44066. }
  44067. this._highLimitsCache[keyOffset] = toValue;
  44068. }
  44069. highLimitValue = this._highLimitsCache[keyOffset];
  44070. offsetValue = this._offsetsCache[keyOffset];
  44071. }
  44072. }
  44073. if (offsetValue === undefined) {
  44074. switch (this._animation.dataType) {
  44075. // Float
  44076. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44077. offsetValue = 0;
  44078. break;
  44079. // Quaternion
  44080. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44081. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44082. break;
  44083. // Vector3
  44084. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44085. offsetValue = BABYLON.Vector3.Zero();
  44086. break;
  44087. // Vector2
  44088. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44089. offsetValue = BABYLON.Vector2.Zero();
  44090. break;
  44091. // Size
  44092. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44093. offsetValue = BABYLON.Size.Zero();
  44094. break;
  44095. // Color3
  44096. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44097. offsetValue = BABYLON.Color3.Black();
  44098. }
  44099. }
  44100. // Compute value
  44101. var repeatCount = (ratio / range) >> 0;
  44102. var currentFrame = returnValue ? from + ratio % range : to;
  44103. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44104. // Set value
  44105. this.setValue(currentValue);
  44106. // Check events
  44107. var events = this._animation.getEvents();
  44108. for (var index = 0; index < events.length; index++) {
  44109. // Make sure current frame has passed event frame and that event frame is within the current range
  44110. // Also, handle both forward and reverse animations
  44111. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44112. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44113. var event = events[index];
  44114. if (!event.isDone) {
  44115. // If event should be done only once, remove it.
  44116. if (event.onlyOnce) {
  44117. events.splice(index, 1);
  44118. index--;
  44119. }
  44120. event.isDone = true;
  44121. event.action();
  44122. } // Don't do anything if the event has already be done.
  44123. }
  44124. else if (events[index].isDone && !events[index].onlyOnce) {
  44125. // reset event, the animation is looping
  44126. events[index].isDone = false;
  44127. }
  44128. }
  44129. if (!returnValue) {
  44130. this._stopped = true;
  44131. }
  44132. return returnValue;
  44133. };
  44134. return RuntimeAnimation;
  44135. }());
  44136. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44137. })(BABYLON || (BABYLON = {}));
  44138. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44139. var BABYLON;
  44140. (function (BABYLON) {
  44141. var Animatable = /** @class */ (function () {
  44142. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44143. if (fromFrame === void 0) { fromFrame = 0; }
  44144. if (toFrame === void 0) { toFrame = 100; }
  44145. if (loopAnimation === void 0) { loopAnimation = false; }
  44146. if (speedRatio === void 0) { speedRatio = 1.0; }
  44147. this.target = target;
  44148. this.fromFrame = fromFrame;
  44149. this.toFrame = toFrame;
  44150. this.loopAnimation = loopAnimation;
  44151. this.onAnimationEnd = onAnimationEnd;
  44152. this._localDelayOffset = null;
  44153. this._pausedDelay = null;
  44154. this._runtimeAnimations = new Array();
  44155. this._paused = false;
  44156. this._speedRatio = 1;
  44157. this.animationStarted = false;
  44158. if (animations) {
  44159. this.appendAnimations(target, animations);
  44160. }
  44161. this._speedRatio = speedRatio;
  44162. this._scene = scene;
  44163. scene._activeAnimatables.push(this);
  44164. }
  44165. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44166. get: function () {
  44167. return this._speedRatio;
  44168. },
  44169. set: function (value) {
  44170. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44171. var animation = this._runtimeAnimations[index];
  44172. animation._prepareForSpeedRatioChange(value);
  44173. }
  44174. this._speedRatio = value;
  44175. },
  44176. enumerable: true,
  44177. configurable: true
  44178. });
  44179. // Methods
  44180. Animatable.prototype.getAnimations = function () {
  44181. return this._runtimeAnimations;
  44182. };
  44183. Animatable.prototype.appendAnimations = function (target, animations) {
  44184. for (var index = 0; index < animations.length; index++) {
  44185. var animation = animations[index];
  44186. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  44187. }
  44188. };
  44189. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  44190. var runtimeAnimations = this._runtimeAnimations;
  44191. for (var index = 0; index < runtimeAnimations.length; index++) {
  44192. if (runtimeAnimations[index].animation.targetProperty === property) {
  44193. return runtimeAnimations[index].animation;
  44194. }
  44195. }
  44196. return null;
  44197. };
  44198. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  44199. var runtimeAnimations = this._runtimeAnimations;
  44200. for (var index = 0; index < runtimeAnimations.length; index++) {
  44201. if (runtimeAnimations[index].animation.targetProperty === property) {
  44202. return runtimeAnimations[index];
  44203. }
  44204. }
  44205. return null;
  44206. };
  44207. Animatable.prototype.reset = function () {
  44208. var runtimeAnimations = this._runtimeAnimations;
  44209. for (var index = 0; index < runtimeAnimations.length; index++) {
  44210. runtimeAnimations[index].reset();
  44211. }
  44212. // Reset to original value
  44213. for (index = 0; index < runtimeAnimations.length; index++) {
  44214. var animation = runtimeAnimations[index];
  44215. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  44216. }
  44217. this._localDelayOffset = null;
  44218. this._pausedDelay = null;
  44219. };
  44220. Animatable.prototype.enableBlending = function (blendingSpeed) {
  44221. var runtimeAnimations = this._runtimeAnimations;
  44222. for (var index = 0; index < runtimeAnimations.length; index++) {
  44223. runtimeAnimations[index].animation.enableBlending = true;
  44224. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  44225. }
  44226. };
  44227. Animatable.prototype.disableBlending = function () {
  44228. var runtimeAnimations = this._runtimeAnimations;
  44229. for (var index = 0; index < runtimeAnimations.length; index++) {
  44230. runtimeAnimations[index].animation.enableBlending = false;
  44231. }
  44232. };
  44233. Animatable.prototype.goToFrame = function (frame) {
  44234. var runtimeAnimations = this._runtimeAnimations;
  44235. if (runtimeAnimations[0]) {
  44236. var fps = runtimeAnimations[0].animation.framePerSecond;
  44237. var currentFrame = runtimeAnimations[0].currentFrame;
  44238. var adjustTime = frame - currentFrame;
  44239. var delay = adjustTime * 1000 / fps;
  44240. if (this._localDelayOffset === null) {
  44241. this._localDelayOffset = 0;
  44242. }
  44243. this._localDelayOffset -= delay;
  44244. }
  44245. for (var index = 0; index < runtimeAnimations.length; index++) {
  44246. runtimeAnimations[index].goToFrame(frame);
  44247. }
  44248. };
  44249. Animatable.prototype.pause = function () {
  44250. if (this._paused) {
  44251. return;
  44252. }
  44253. this._paused = true;
  44254. };
  44255. Animatable.prototype.restart = function () {
  44256. this._paused = false;
  44257. };
  44258. Animatable.prototype.stop = function (animationName) {
  44259. if (animationName) {
  44260. var idx = this._scene._activeAnimatables.indexOf(this);
  44261. if (idx > -1) {
  44262. var runtimeAnimations = this._runtimeAnimations;
  44263. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  44264. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  44265. continue;
  44266. }
  44267. runtimeAnimations[index].dispose();
  44268. runtimeAnimations.splice(index, 1);
  44269. }
  44270. if (runtimeAnimations.length == 0) {
  44271. this._scene._activeAnimatables.splice(idx, 1);
  44272. if (this.onAnimationEnd) {
  44273. this.onAnimationEnd();
  44274. }
  44275. }
  44276. }
  44277. }
  44278. else {
  44279. var index = this._scene._activeAnimatables.indexOf(this);
  44280. if (index > -1) {
  44281. this._scene._activeAnimatables.splice(index, 1);
  44282. var runtimeAnimations = this._runtimeAnimations;
  44283. for (var index = 0; index < runtimeAnimations.length; index++) {
  44284. runtimeAnimations[index].dispose();
  44285. }
  44286. if (this.onAnimationEnd) {
  44287. this.onAnimationEnd();
  44288. }
  44289. }
  44290. }
  44291. };
  44292. Animatable.prototype._animate = function (delay) {
  44293. if (this._paused) {
  44294. this.animationStarted = false;
  44295. if (this._pausedDelay === null) {
  44296. this._pausedDelay = delay;
  44297. }
  44298. return true;
  44299. }
  44300. if (this._localDelayOffset === null) {
  44301. this._localDelayOffset = delay;
  44302. this._pausedDelay = null;
  44303. }
  44304. else if (this._pausedDelay !== null) {
  44305. this._localDelayOffset += delay - this._pausedDelay;
  44306. this._pausedDelay = null;
  44307. }
  44308. // Animating
  44309. var running = false;
  44310. var runtimeAnimations = this._runtimeAnimations;
  44311. var index;
  44312. for (index = 0; index < runtimeAnimations.length; index++) {
  44313. var animation = runtimeAnimations[index];
  44314. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  44315. running = running || isRunning;
  44316. }
  44317. this.animationStarted = running;
  44318. if (!running) {
  44319. // Remove from active animatables
  44320. index = this._scene._activeAnimatables.indexOf(this);
  44321. this._scene._activeAnimatables.splice(index, 1);
  44322. // Dispose all runtime animations
  44323. for (index = 0; index < runtimeAnimations.length; index++) {
  44324. runtimeAnimations[index].dispose();
  44325. }
  44326. }
  44327. if (!running && this.onAnimationEnd) {
  44328. this.onAnimationEnd();
  44329. this.onAnimationEnd = null;
  44330. }
  44331. return running;
  44332. };
  44333. return Animatable;
  44334. }());
  44335. BABYLON.Animatable = Animatable;
  44336. })(BABYLON || (BABYLON = {}));
  44337. //# sourceMappingURL=babylon.animatable.js.map
  44338. var BABYLON;
  44339. (function (BABYLON) {
  44340. var EasingFunction = /** @class */ (function () {
  44341. function EasingFunction() {
  44342. // Properties
  44343. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  44344. }
  44345. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  44346. get: function () {
  44347. return EasingFunction._EASINGMODE_EASEIN;
  44348. },
  44349. enumerable: true,
  44350. configurable: true
  44351. });
  44352. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  44353. get: function () {
  44354. return EasingFunction._EASINGMODE_EASEOUT;
  44355. },
  44356. enumerable: true,
  44357. configurable: true
  44358. });
  44359. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  44360. get: function () {
  44361. return EasingFunction._EASINGMODE_EASEINOUT;
  44362. },
  44363. enumerable: true,
  44364. configurable: true
  44365. });
  44366. EasingFunction.prototype.setEasingMode = function (easingMode) {
  44367. var n = Math.min(Math.max(easingMode, 0), 2);
  44368. this._easingMode = n;
  44369. };
  44370. EasingFunction.prototype.getEasingMode = function () {
  44371. return this._easingMode;
  44372. };
  44373. EasingFunction.prototype.easeInCore = function (gradient) {
  44374. throw new Error('You must implement this method');
  44375. };
  44376. EasingFunction.prototype.ease = function (gradient) {
  44377. switch (this._easingMode) {
  44378. case EasingFunction.EASINGMODE_EASEIN:
  44379. return this.easeInCore(gradient);
  44380. case EasingFunction.EASINGMODE_EASEOUT:
  44381. return (1 - this.easeInCore(1 - gradient));
  44382. }
  44383. if (gradient >= 0.5) {
  44384. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  44385. }
  44386. return (this.easeInCore(gradient * 2) * 0.5);
  44387. };
  44388. //Statics
  44389. EasingFunction._EASINGMODE_EASEIN = 0;
  44390. EasingFunction._EASINGMODE_EASEOUT = 1;
  44391. EasingFunction._EASINGMODE_EASEINOUT = 2;
  44392. return EasingFunction;
  44393. }());
  44394. BABYLON.EasingFunction = EasingFunction;
  44395. var CircleEase = /** @class */ (function (_super) {
  44396. __extends(CircleEase, _super);
  44397. function CircleEase() {
  44398. return _super !== null && _super.apply(this, arguments) || this;
  44399. }
  44400. CircleEase.prototype.easeInCore = function (gradient) {
  44401. gradient = Math.max(0, Math.min(1, gradient));
  44402. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  44403. };
  44404. return CircleEase;
  44405. }(EasingFunction));
  44406. BABYLON.CircleEase = CircleEase;
  44407. var BackEase = /** @class */ (function (_super) {
  44408. __extends(BackEase, _super);
  44409. function BackEase(amplitude) {
  44410. if (amplitude === void 0) { amplitude = 1; }
  44411. var _this = _super.call(this) || this;
  44412. _this.amplitude = amplitude;
  44413. return _this;
  44414. }
  44415. BackEase.prototype.easeInCore = function (gradient) {
  44416. var num = Math.max(0, this.amplitude);
  44417. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  44418. };
  44419. return BackEase;
  44420. }(EasingFunction));
  44421. BABYLON.BackEase = BackEase;
  44422. var BounceEase = /** @class */ (function (_super) {
  44423. __extends(BounceEase, _super);
  44424. function BounceEase(bounces, bounciness) {
  44425. if (bounces === void 0) { bounces = 3; }
  44426. if (bounciness === void 0) { bounciness = 2; }
  44427. var _this = _super.call(this) || this;
  44428. _this.bounces = bounces;
  44429. _this.bounciness = bounciness;
  44430. return _this;
  44431. }
  44432. BounceEase.prototype.easeInCore = function (gradient) {
  44433. var y = Math.max(0.0, this.bounces);
  44434. var bounciness = this.bounciness;
  44435. if (bounciness <= 1.0) {
  44436. bounciness = 1.001;
  44437. }
  44438. var num9 = Math.pow(bounciness, y);
  44439. var num5 = 1.0 - bounciness;
  44440. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44441. var num15 = gradient * num4;
  44442. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44443. var num3 = Math.floor(num65);
  44444. var num13 = num3 + 1.0;
  44445. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44446. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44447. var num7 = (num8 + num12) * 0.5;
  44448. var num6 = gradient - num7;
  44449. var num2 = num7 - num8;
  44450. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44451. };
  44452. return BounceEase;
  44453. }(EasingFunction));
  44454. BABYLON.BounceEase = BounceEase;
  44455. var CubicEase = /** @class */ (function (_super) {
  44456. __extends(CubicEase, _super);
  44457. function CubicEase() {
  44458. return _super !== null && _super.apply(this, arguments) || this;
  44459. }
  44460. CubicEase.prototype.easeInCore = function (gradient) {
  44461. return (gradient * gradient * gradient);
  44462. };
  44463. return CubicEase;
  44464. }(EasingFunction));
  44465. BABYLON.CubicEase = CubicEase;
  44466. var ElasticEase = /** @class */ (function (_super) {
  44467. __extends(ElasticEase, _super);
  44468. function ElasticEase(oscillations, springiness) {
  44469. if (oscillations === void 0) { oscillations = 3; }
  44470. if (springiness === void 0) { springiness = 3; }
  44471. var _this = _super.call(this) || this;
  44472. _this.oscillations = oscillations;
  44473. _this.springiness = springiness;
  44474. return _this;
  44475. }
  44476. ElasticEase.prototype.easeInCore = function (gradient) {
  44477. var num2;
  44478. var num3 = Math.max(0.0, this.oscillations);
  44479. var num = Math.max(0.0, this.springiness);
  44480. if (num == 0) {
  44481. num2 = gradient;
  44482. }
  44483. else {
  44484. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44485. }
  44486. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44487. };
  44488. return ElasticEase;
  44489. }(EasingFunction));
  44490. BABYLON.ElasticEase = ElasticEase;
  44491. var ExponentialEase = /** @class */ (function (_super) {
  44492. __extends(ExponentialEase, _super);
  44493. function ExponentialEase(exponent) {
  44494. if (exponent === void 0) { exponent = 2; }
  44495. var _this = _super.call(this) || this;
  44496. _this.exponent = exponent;
  44497. return _this;
  44498. }
  44499. ExponentialEase.prototype.easeInCore = function (gradient) {
  44500. if (this.exponent <= 0) {
  44501. return gradient;
  44502. }
  44503. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44504. };
  44505. return ExponentialEase;
  44506. }(EasingFunction));
  44507. BABYLON.ExponentialEase = ExponentialEase;
  44508. var PowerEase = /** @class */ (function (_super) {
  44509. __extends(PowerEase, _super);
  44510. function PowerEase(power) {
  44511. if (power === void 0) { power = 2; }
  44512. var _this = _super.call(this) || this;
  44513. _this.power = power;
  44514. return _this;
  44515. }
  44516. PowerEase.prototype.easeInCore = function (gradient) {
  44517. var y = Math.max(0.0, this.power);
  44518. return Math.pow(gradient, y);
  44519. };
  44520. return PowerEase;
  44521. }(EasingFunction));
  44522. BABYLON.PowerEase = PowerEase;
  44523. var QuadraticEase = /** @class */ (function (_super) {
  44524. __extends(QuadraticEase, _super);
  44525. function QuadraticEase() {
  44526. return _super !== null && _super.apply(this, arguments) || this;
  44527. }
  44528. QuadraticEase.prototype.easeInCore = function (gradient) {
  44529. return (gradient * gradient);
  44530. };
  44531. return QuadraticEase;
  44532. }(EasingFunction));
  44533. BABYLON.QuadraticEase = QuadraticEase;
  44534. var QuarticEase = /** @class */ (function (_super) {
  44535. __extends(QuarticEase, _super);
  44536. function QuarticEase() {
  44537. return _super !== null && _super.apply(this, arguments) || this;
  44538. }
  44539. QuarticEase.prototype.easeInCore = function (gradient) {
  44540. return (gradient * gradient * gradient * gradient);
  44541. };
  44542. return QuarticEase;
  44543. }(EasingFunction));
  44544. BABYLON.QuarticEase = QuarticEase;
  44545. var QuinticEase = /** @class */ (function (_super) {
  44546. __extends(QuinticEase, _super);
  44547. function QuinticEase() {
  44548. return _super !== null && _super.apply(this, arguments) || this;
  44549. }
  44550. QuinticEase.prototype.easeInCore = function (gradient) {
  44551. return (gradient * gradient * gradient * gradient * gradient);
  44552. };
  44553. return QuinticEase;
  44554. }(EasingFunction));
  44555. BABYLON.QuinticEase = QuinticEase;
  44556. var SineEase = /** @class */ (function (_super) {
  44557. __extends(SineEase, _super);
  44558. function SineEase() {
  44559. return _super !== null && _super.apply(this, arguments) || this;
  44560. }
  44561. SineEase.prototype.easeInCore = function (gradient) {
  44562. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44563. };
  44564. return SineEase;
  44565. }(EasingFunction));
  44566. BABYLON.SineEase = SineEase;
  44567. var BezierCurveEase = /** @class */ (function (_super) {
  44568. __extends(BezierCurveEase, _super);
  44569. function BezierCurveEase(x1, y1, x2, y2) {
  44570. if (x1 === void 0) { x1 = 0; }
  44571. if (y1 === void 0) { y1 = 0; }
  44572. if (x2 === void 0) { x2 = 1; }
  44573. if (y2 === void 0) { y2 = 1; }
  44574. var _this = _super.call(this) || this;
  44575. _this.x1 = x1;
  44576. _this.y1 = y1;
  44577. _this.x2 = x2;
  44578. _this.y2 = y2;
  44579. return _this;
  44580. }
  44581. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44582. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44583. };
  44584. return BezierCurveEase;
  44585. }(EasingFunction));
  44586. BABYLON.BezierCurveEase = BezierCurveEase;
  44587. })(BABYLON || (BABYLON = {}));
  44588. //# sourceMappingURL=babylon.easing.js.map
  44589. var BABYLON;
  44590. (function (BABYLON) {
  44591. var Condition = /** @class */ (function () {
  44592. function Condition(actionManager) {
  44593. this._actionManager = actionManager;
  44594. }
  44595. Condition.prototype.isValid = function () {
  44596. return true;
  44597. };
  44598. Condition.prototype._getProperty = function (propertyPath) {
  44599. return this._actionManager._getProperty(propertyPath);
  44600. };
  44601. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44602. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44603. };
  44604. Condition.prototype.serialize = function () {
  44605. };
  44606. Condition.prototype._serialize = function (serializedCondition) {
  44607. return {
  44608. type: 2,
  44609. children: [],
  44610. name: serializedCondition.name,
  44611. properties: serializedCondition.properties
  44612. };
  44613. };
  44614. return Condition;
  44615. }());
  44616. BABYLON.Condition = Condition;
  44617. var ValueCondition = /** @class */ (function (_super) {
  44618. __extends(ValueCondition, _super);
  44619. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44620. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44621. var _this = _super.call(this, actionManager) || this;
  44622. _this.propertyPath = propertyPath;
  44623. _this.value = value;
  44624. _this.operator = operator;
  44625. _this._target = target;
  44626. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44627. _this._property = _this._getProperty(_this.propertyPath);
  44628. return _this;
  44629. }
  44630. Object.defineProperty(ValueCondition, "IsEqual", {
  44631. get: function () {
  44632. return ValueCondition._IsEqual;
  44633. },
  44634. enumerable: true,
  44635. configurable: true
  44636. });
  44637. Object.defineProperty(ValueCondition, "IsDifferent", {
  44638. get: function () {
  44639. return ValueCondition._IsDifferent;
  44640. },
  44641. enumerable: true,
  44642. configurable: true
  44643. });
  44644. Object.defineProperty(ValueCondition, "IsGreater", {
  44645. get: function () {
  44646. return ValueCondition._IsGreater;
  44647. },
  44648. enumerable: true,
  44649. configurable: true
  44650. });
  44651. Object.defineProperty(ValueCondition, "IsLesser", {
  44652. get: function () {
  44653. return ValueCondition._IsLesser;
  44654. },
  44655. enumerable: true,
  44656. configurable: true
  44657. });
  44658. // Methods
  44659. ValueCondition.prototype.isValid = function () {
  44660. switch (this.operator) {
  44661. case ValueCondition.IsGreater:
  44662. return this._effectiveTarget[this._property] > this.value;
  44663. case ValueCondition.IsLesser:
  44664. return this._effectiveTarget[this._property] < this.value;
  44665. case ValueCondition.IsEqual:
  44666. case ValueCondition.IsDifferent:
  44667. var check;
  44668. if (this.value.equals) {
  44669. check = this.value.equals(this._effectiveTarget[this._property]);
  44670. }
  44671. else {
  44672. check = this.value === this._effectiveTarget[this._property];
  44673. }
  44674. return this.operator === ValueCondition.IsEqual ? check : !check;
  44675. }
  44676. return false;
  44677. };
  44678. ValueCondition.prototype.serialize = function () {
  44679. return this._serialize({
  44680. name: "ValueCondition",
  44681. properties: [
  44682. BABYLON.Action._GetTargetProperty(this._target),
  44683. { name: "propertyPath", value: this.propertyPath },
  44684. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44685. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44686. ]
  44687. });
  44688. };
  44689. ValueCondition.GetOperatorName = function (operator) {
  44690. switch (operator) {
  44691. case ValueCondition._IsEqual: return "IsEqual";
  44692. case ValueCondition._IsDifferent: return "IsDifferent";
  44693. case ValueCondition._IsGreater: return "IsGreater";
  44694. case ValueCondition._IsLesser: return "IsLesser";
  44695. default: return "";
  44696. }
  44697. };
  44698. // Statics
  44699. ValueCondition._IsEqual = 0;
  44700. ValueCondition._IsDifferent = 1;
  44701. ValueCondition._IsGreater = 2;
  44702. ValueCondition._IsLesser = 3;
  44703. return ValueCondition;
  44704. }(Condition));
  44705. BABYLON.ValueCondition = ValueCondition;
  44706. var PredicateCondition = /** @class */ (function (_super) {
  44707. __extends(PredicateCondition, _super);
  44708. function PredicateCondition(actionManager, predicate) {
  44709. var _this = _super.call(this, actionManager) || this;
  44710. _this.predicate = predicate;
  44711. return _this;
  44712. }
  44713. PredicateCondition.prototype.isValid = function () {
  44714. return this.predicate();
  44715. };
  44716. return PredicateCondition;
  44717. }(Condition));
  44718. BABYLON.PredicateCondition = PredicateCondition;
  44719. var StateCondition = /** @class */ (function (_super) {
  44720. __extends(StateCondition, _super);
  44721. function StateCondition(actionManager, target, value) {
  44722. var _this = _super.call(this, actionManager) || this;
  44723. _this.value = value;
  44724. _this._target = target;
  44725. return _this;
  44726. }
  44727. // Methods
  44728. StateCondition.prototype.isValid = function () {
  44729. return this._target.state === this.value;
  44730. };
  44731. StateCondition.prototype.serialize = function () {
  44732. return this._serialize({
  44733. name: "StateCondition",
  44734. properties: [
  44735. BABYLON.Action._GetTargetProperty(this._target),
  44736. { name: "value", value: this.value }
  44737. ]
  44738. });
  44739. };
  44740. return StateCondition;
  44741. }(Condition));
  44742. BABYLON.StateCondition = StateCondition;
  44743. })(BABYLON || (BABYLON = {}));
  44744. //# sourceMappingURL=babylon.condition.js.map
  44745. var BABYLON;
  44746. (function (BABYLON) {
  44747. var Action = /** @class */ (function () {
  44748. function Action(triggerOptions, condition) {
  44749. this.triggerOptions = triggerOptions;
  44750. this.onBeforeExecuteObservable = new BABYLON.Observable();
  44751. if (triggerOptions.parameter) {
  44752. this.trigger = triggerOptions.trigger;
  44753. this._triggerParameter = triggerOptions.parameter;
  44754. }
  44755. else {
  44756. this.trigger = triggerOptions;
  44757. }
  44758. this._nextActiveAction = this;
  44759. this._condition = condition;
  44760. }
  44761. // Methods
  44762. Action.prototype._prepare = function () {
  44763. };
  44764. Action.prototype.getTriggerParameter = function () {
  44765. return this._triggerParameter;
  44766. };
  44767. Action.prototype._executeCurrent = function (evt) {
  44768. if (this._nextActiveAction._condition) {
  44769. var condition = this._nextActiveAction._condition;
  44770. var currentRenderId = this._actionManager.getScene().getRenderId();
  44771. // We cache the current evaluation for the current frame
  44772. if (condition._evaluationId === currentRenderId) {
  44773. if (!condition._currentResult) {
  44774. return;
  44775. }
  44776. }
  44777. else {
  44778. condition._evaluationId = currentRenderId;
  44779. if (!condition.isValid()) {
  44780. condition._currentResult = false;
  44781. return;
  44782. }
  44783. condition._currentResult = true;
  44784. }
  44785. }
  44786. this.onBeforeExecuteObservable.notifyObservers(this);
  44787. this._nextActiveAction.execute(evt);
  44788. this.skipToNextActiveAction();
  44789. };
  44790. Action.prototype.execute = function (evt) {
  44791. };
  44792. Action.prototype.skipToNextActiveAction = function () {
  44793. if (this._nextActiveAction._child) {
  44794. if (!this._nextActiveAction._child._actionManager) {
  44795. this._nextActiveAction._child._actionManager = this._actionManager;
  44796. }
  44797. this._nextActiveAction = this._nextActiveAction._child;
  44798. }
  44799. else {
  44800. this._nextActiveAction = this;
  44801. }
  44802. };
  44803. Action.prototype.then = function (action) {
  44804. this._child = action;
  44805. action._actionManager = this._actionManager;
  44806. action._prepare();
  44807. return action;
  44808. };
  44809. Action.prototype._getProperty = function (propertyPath) {
  44810. return this._actionManager._getProperty(propertyPath);
  44811. };
  44812. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  44813. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44814. };
  44815. Action.prototype.serialize = function (parent) {
  44816. };
  44817. // Called by BABYLON.Action objects in serialize(...). Internal use
  44818. Action.prototype._serialize = function (serializedAction, parent) {
  44819. var serializationObject = {
  44820. type: 1,
  44821. children: [],
  44822. name: serializedAction.name,
  44823. properties: serializedAction.properties || []
  44824. };
  44825. // Serialize child
  44826. if (this._child) {
  44827. this._child.serialize(serializationObject);
  44828. }
  44829. // Check if "this" has a condition
  44830. if (this._condition) {
  44831. var serializedCondition = this._condition.serialize();
  44832. serializedCondition.children.push(serializationObject);
  44833. if (parent) {
  44834. parent.children.push(serializedCondition);
  44835. }
  44836. return serializedCondition;
  44837. }
  44838. if (parent) {
  44839. parent.children.push(serializationObject);
  44840. }
  44841. return serializationObject;
  44842. };
  44843. Action._SerializeValueAsString = function (value) {
  44844. if (typeof value === "number") {
  44845. return value.toString();
  44846. }
  44847. if (typeof value === "boolean") {
  44848. return value ? "true" : "false";
  44849. }
  44850. if (value instanceof BABYLON.Vector2) {
  44851. return value.x + ", " + value.y;
  44852. }
  44853. if (value instanceof BABYLON.Vector3) {
  44854. return value.x + ", " + value.y + ", " + value.z;
  44855. }
  44856. if (value instanceof BABYLON.Color3) {
  44857. return value.r + ", " + value.g + ", " + value.b;
  44858. }
  44859. if (value instanceof BABYLON.Color4) {
  44860. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  44861. }
  44862. return value; // string
  44863. };
  44864. Action._GetTargetProperty = function (target) {
  44865. return {
  44866. name: "target",
  44867. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  44868. : target instanceof BABYLON.Light ? "LightProperties"
  44869. : target instanceof BABYLON.Camera ? "CameraProperties"
  44870. : "SceneProperties",
  44871. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  44872. };
  44873. };
  44874. return Action;
  44875. }());
  44876. BABYLON.Action = Action;
  44877. })(BABYLON || (BABYLON = {}));
  44878. //# sourceMappingURL=babylon.action.js.map
  44879. var BABYLON;
  44880. (function (BABYLON) {
  44881. /**
  44882. * ActionEvent is the event beint sent when an action is triggered.
  44883. */
  44884. var ActionEvent = /** @class */ (function () {
  44885. /**
  44886. * @param source The mesh or sprite that triggered the action.
  44887. * @param pointerX The X mouse cursor position at the time of the event
  44888. * @param pointerY The Y mouse cursor position at the time of the event
  44889. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  44890. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  44891. */
  44892. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  44893. this.source = source;
  44894. this.pointerX = pointerX;
  44895. this.pointerY = pointerY;
  44896. this.meshUnderPointer = meshUnderPointer;
  44897. this.sourceEvent = sourceEvent;
  44898. this.additionalData = additionalData;
  44899. }
  44900. /**
  44901. * Helper function to auto-create an ActionEvent from a source mesh.
  44902. * @param source The source mesh that triggered the event
  44903. * @param evt {Event} The original (browser) event
  44904. */
  44905. ActionEvent.CreateNew = function (source, evt, additionalData) {
  44906. var scene = source.getScene();
  44907. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44908. };
  44909. /**
  44910. * Helper function to auto-create an ActionEvent from a source mesh.
  44911. * @param source The source sprite that triggered the event
  44912. * @param scene Scene associated with the sprite
  44913. * @param evt {Event} The original (browser) event
  44914. */
  44915. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  44916. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44917. };
  44918. /**
  44919. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  44920. * @param scene the scene where the event occurred
  44921. * @param evt {Event} The original (browser) event
  44922. */
  44923. ActionEvent.CreateNewFromScene = function (scene, evt) {
  44924. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  44925. };
  44926. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  44927. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  44928. };
  44929. return ActionEvent;
  44930. }());
  44931. BABYLON.ActionEvent = ActionEvent;
  44932. /**
  44933. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  44934. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  44935. */
  44936. var ActionManager = /** @class */ (function () {
  44937. function ActionManager(scene) {
  44938. // Members
  44939. this.actions = new Array();
  44940. this.hoverCursor = '';
  44941. this._scene = scene;
  44942. scene._actionManagers.push(this);
  44943. }
  44944. Object.defineProperty(ActionManager, "NothingTrigger", {
  44945. get: function () {
  44946. return ActionManager._NothingTrigger;
  44947. },
  44948. enumerable: true,
  44949. configurable: true
  44950. });
  44951. Object.defineProperty(ActionManager, "OnPickTrigger", {
  44952. get: function () {
  44953. return ActionManager._OnPickTrigger;
  44954. },
  44955. enumerable: true,
  44956. configurable: true
  44957. });
  44958. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  44959. get: function () {
  44960. return ActionManager._OnLeftPickTrigger;
  44961. },
  44962. enumerable: true,
  44963. configurable: true
  44964. });
  44965. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  44966. get: function () {
  44967. return ActionManager._OnRightPickTrigger;
  44968. },
  44969. enumerable: true,
  44970. configurable: true
  44971. });
  44972. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  44973. get: function () {
  44974. return ActionManager._OnCenterPickTrigger;
  44975. },
  44976. enumerable: true,
  44977. configurable: true
  44978. });
  44979. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  44980. get: function () {
  44981. return ActionManager._OnPickDownTrigger;
  44982. },
  44983. enumerable: true,
  44984. configurable: true
  44985. });
  44986. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  44987. get: function () {
  44988. return ActionManager._OnDoublePickTrigger;
  44989. },
  44990. enumerable: true,
  44991. configurable: true
  44992. });
  44993. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  44994. get: function () {
  44995. return ActionManager._OnPickUpTrigger;
  44996. },
  44997. enumerable: true,
  44998. configurable: true
  44999. });
  45000. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45001. /// This trigger will only be raised if you also declared a OnPickDown
  45002. get: function () {
  45003. return ActionManager._OnPickOutTrigger;
  45004. },
  45005. enumerable: true,
  45006. configurable: true
  45007. });
  45008. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45009. get: function () {
  45010. return ActionManager._OnLongPressTrigger;
  45011. },
  45012. enumerable: true,
  45013. configurable: true
  45014. });
  45015. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45016. get: function () {
  45017. return ActionManager._OnPointerOverTrigger;
  45018. },
  45019. enumerable: true,
  45020. configurable: true
  45021. });
  45022. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45023. get: function () {
  45024. return ActionManager._OnPointerOutTrigger;
  45025. },
  45026. enumerable: true,
  45027. configurable: true
  45028. });
  45029. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45030. get: function () {
  45031. return ActionManager._OnEveryFrameTrigger;
  45032. },
  45033. enumerable: true,
  45034. configurable: true
  45035. });
  45036. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45037. get: function () {
  45038. return ActionManager._OnIntersectionEnterTrigger;
  45039. },
  45040. enumerable: true,
  45041. configurable: true
  45042. });
  45043. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45044. get: function () {
  45045. return ActionManager._OnIntersectionExitTrigger;
  45046. },
  45047. enumerable: true,
  45048. configurable: true
  45049. });
  45050. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45051. get: function () {
  45052. return ActionManager._OnKeyDownTrigger;
  45053. },
  45054. enumerable: true,
  45055. configurable: true
  45056. });
  45057. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45058. get: function () {
  45059. return ActionManager._OnKeyUpTrigger;
  45060. },
  45061. enumerable: true,
  45062. configurable: true
  45063. });
  45064. // Methods
  45065. ActionManager.prototype.dispose = function () {
  45066. var index = this._scene._actionManagers.indexOf(this);
  45067. for (var i = 0; i < this.actions.length; i++) {
  45068. var action = this.actions[i];
  45069. ActionManager.Triggers[action.trigger]--;
  45070. if (ActionManager.Triggers[action.trigger] === 0) {
  45071. delete ActionManager.Triggers[action.trigger];
  45072. }
  45073. }
  45074. if (index > -1) {
  45075. this._scene._actionManagers.splice(index, 1);
  45076. }
  45077. };
  45078. ActionManager.prototype.getScene = function () {
  45079. return this._scene;
  45080. };
  45081. /**
  45082. * Does this action manager handles actions of any of the given triggers
  45083. * @param {number[]} triggers - the triggers to be tested
  45084. * @return {boolean} whether one (or more) of the triggers is handeled
  45085. */
  45086. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45087. for (var index = 0; index < this.actions.length; index++) {
  45088. var action = this.actions[index];
  45089. if (triggers.indexOf(action.trigger) > -1) {
  45090. return true;
  45091. }
  45092. }
  45093. return false;
  45094. };
  45095. /**
  45096. * Does this action manager handles actions of a given trigger
  45097. * @param {number} trigger - the trigger to be tested
  45098. * @return {boolean} whether the trigger is handeled
  45099. */
  45100. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45101. for (var index = 0; index < this.actions.length; index++) {
  45102. var action = this.actions[index];
  45103. if (action.trigger === trigger) {
  45104. return true;
  45105. }
  45106. }
  45107. return false;
  45108. };
  45109. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45110. /**
  45111. * Does this action manager has pointer triggers
  45112. * @return {boolean} whether or not it has pointer triggers
  45113. */
  45114. get: function () {
  45115. for (var index = 0; index < this.actions.length; index++) {
  45116. var action = this.actions[index];
  45117. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45118. return true;
  45119. }
  45120. }
  45121. return false;
  45122. },
  45123. enumerable: true,
  45124. configurable: true
  45125. });
  45126. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45127. /**
  45128. * Does this action manager has pick triggers
  45129. * @return {boolean} whether or not it has pick triggers
  45130. */
  45131. get: function () {
  45132. for (var index = 0; index < this.actions.length; index++) {
  45133. var action = this.actions[index];
  45134. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45135. return true;
  45136. }
  45137. }
  45138. return false;
  45139. },
  45140. enumerable: true,
  45141. configurable: true
  45142. });
  45143. Object.defineProperty(ActionManager, "HasTriggers", {
  45144. /**
  45145. * Does exist one action manager with at least one trigger
  45146. * @return {boolean} whether or not it exists one action manager with one trigger
  45147. **/
  45148. get: function () {
  45149. for (var t in ActionManager.Triggers) {
  45150. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45151. return true;
  45152. }
  45153. }
  45154. return false;
  45155. },
  45156. enumerable: true,
  45157. configurable: true
  45158. });
  45159. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45160. /**
  45161. * Does exist one action manager with at least one pick trigger
  45162. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45163. **/
  45164. get: function () {
  45165. for (var t in ActionManager.Triggers) {
  45166. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45167. var t_int = parseInt(t);
  45168. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45169. return true;
  45170. }
  45171. }
  45172. }
  45173. return false;
  45174. },
  45175. enumerable: true,
  45176. configurable: true
  45177. });
  45178. /**
  45179. * Does exist one action manager that handles actions of a given trigger
  45180. * @param {number} trigger - the trigger to be tested
  45181. * @return {boolean} whether the trigger is handeled by at least one action manager
  45182. **/
  45183. ActionManager.HasSpecificTrigger = function (trigger) {
  45184. for (var t in ActionManager.Triggers) {
  45185. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45186. var t_int = parseInt(t);
  45187. if (t_int === trigger) {
  45188. return true;
  45189. }
  45190. }
  45191. }
  45192. return false;
  45193. };
  45194. /**
  45195. * Registers an action to this action manager
  45196. * @param {BABYLON.Action} action - the action to be registered
  45197. * @return {BABYLON.Action} the action amended (prepared) after registration
  45198. */
  45199. ActionManager.prototype.registerAction = function (action) {
  45200. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  45201. if (this.getScene().actionManager !== this) {
  45202. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  45203. return null;
  45204. }
  45205. }
  45206. this.actions.push(action);
  45207. if (ActionManager.Triggers[action.trigger]) {
  45208. ActionManager.Triggers[action.trigger]++;
  45209. }
  45210. else {
  45211. ActionManager.Triggers[action.trigger] = 1;
  45212. }
  45213. action._actionManager = this;
  45214. action._prepare();
  45215. return action;
  45216. };
  45217. /**
  45218. * Unregisters an action to this action manager
  45219. * @param action The action to be unregistered
  45220. * @return whether the action has been unregistered
  45221. */
  45222. ActionManager.prototype.unregisterAction = function (action) {
  45223. var index = this.actions.indexOf(action);
  45224. if (index !== -1) {
  45225. this.actions.splice(index, 1);
  45226. ActionManager.Triggers[action.trigger] -= 1;
  45227. if (ActionManager.Triggers[action.trigger] === 0) {
  45228. delete ActionManager.Triggers[action.trigger];
  45229. }
  45230. delete action._actionManager;
  45231. return true;
  45232. }
  45233. return false;
  45234. };
  45235. /**
  45236. * Process a specific trigger
  45237. * @param {number} trigger - the trigger to process
  45238. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45239. */
  45240. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45241. for (var index = 0; index < this.actions.length; index++) {
  45242. var action = this.actions[index];
  45243. if (action.trigger === trigger) {
  45244. if (evt) {
  45245. if (trigger === ActionManager.OnKeyUpTrigger
  45246. || trigger === ActionManager.OnKeyDownTrigger) {
  45247. var parameter = action.getTriggerParameter();
  45248. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45249. if (!parameter.toLowerCase) {
  45250. continue;
  45251. }
  45252. var lowerCase = parameter.toLowerCase();
  45253. if (lowerCase !== evt.sourceEvent.key) {
  45254. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45255. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45256. if (actualkey !== lowerCase) {
  45257. continue;
  45258. }
  45259. }
  45260. }
  45261. }
  45262. }
  45263. action._executeCurrent(evt);
  45264. }
  45265. }
  45266. };
  45267. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45268. var properties = propertyPath.split(".");
  45269. for (var index = 0; index < properties.length - 1; index++) {
  45270. target = target[properties[index]];
  45271. }
  45272. return target;
  45273. };
  45274. ActionManager.prototype._getProperty = function (propertyPath) {
  45275. var properties = propertyPath.split(".");
  45276. return properties[properties.length - 1];
  45277. };
  45278. ActionManager.prototype.serialize = function (name) {
  45279. var root = {
  45280. children: new Array(),
  45281. name: name,
  45282. type: 3,
  45283. properties: new Array() // Empty for root but required
  45284. };
  45285. for (var i = 0; i < this.actions.length; i++) {
  45286. var triggerObject = {
  45287. type: 0,
  45288. children: new Array(),
  45289. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45290. properties: new Array()
  45291. };
  45292. var triggerOptions = this.actions[i].triggerOptions;
  45293. if (triggerOptions && typeof triggerOptions !== "number") {
  45294. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45295. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45296. }
  45297. else {
  45298. var parameter = {};
  45299. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45300. if (triggerOptions.parameter.mesh) {
  45301. parameter._meshId = triggerOptions.parameter.mesh.id;
  45302. }
  45303. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45304. }
  45305. }
  45306. // Serialize child action, recursively
  45307. this.actions[i].serialize(triggerObject);
  45308. // Add serialized trigger
  45309. root.children.push(triggerObject);
  45310. }
  45311. return root;
  45312. };
  45313. ActionManager.Parse = function (parsedActions, object, scene) {
  45314. var actionManager = new ActionManager(scene);
  45315. if (object === null)
  45316. scene.actionManager = actionManager;
  45317. else
  45318. object.actionManager = actionManager;
  45319. // instanciate a new object
  45320. var instanciate = function (name, params) {
  45321. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  45322. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  45323. newInstance.constructor.apply(newInstance, params);
  45324. return newInstance;
  45325. };
  45326. var parseParameter = function (name, value, target, propertyPath) {
  45327. if (propertyPath === null) {
  45328. // String, boolean or float
  45329. var floatValue = parseFloat(value);
  45330. if (value === "true" || value === "false")
  45331. return value === "true";
  45332. else
  45333. return isNaN(floatValue) ? value : floatValue;
  45334. }
  45335. var effectiveTarget = propertyPath.split(".");
  45336. var values = value.split(",");
  45337. // Get effective Target
  45338. for (var i = 0; i < effectiveTarget.length; i++) {
  45339. target = target[effectiveTarget[i]];
  45340. }
  45341. // Return appropriate value with its type
  45342. if (typeof (target) === "boolean")
  45343. return values[0] === "true";
  45344. if (typeof (target) === "string")
  45345. return values[0];
  45346. // Parameters with multiple values such as Vector3 etc.
  45347. var split = new Array();
  45348. for (var i = 0; i < values.length; i++)
  45349. split.push(parseFloat(values[i]));
  45350. if (target instanceof BABYLON.Vector3)
  45351. return BABYLON.Vector3.FromArray(split);
  45352. if (target instanceof BABYLON.Vector4)
  45353. return BABYLON.Vector4.FromArray(split);
  45354. if (target instanceof BABYLON.Color3)
  45355. return BABYLON.Color3.FromArray(split);
  45356. if (target instanceof BABYLON.Color4)
  45357. return BABYLON.Color4.FromArray(split);
  45358. return parseFloat(values[0]);
  45359. };
  45360. // traverse graph per trigger
  45361. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45362. if (combineArray === void 0) { combineArray = null; }
  45363. if (parsedAction.detached)
  45364. return;
  45365. var parameters = new Array();
  45366. var target = null;
  45367. var propertyPath = null;
  45368. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45369. // Parameters
  45370. if (parsedAction.type === 2)
  45371. parameters.push(actionManager);
  45372. else
  45373. parameters.push(trigger);
  45374. if (combine) {
  45375. var actions = new Array();
  45376. for (var j = 0; j < parsedAction.combine.length; j++) {
  45377. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  45378. }
  45379. parameters.push(actions);
  45380. }
  45381. else {
  45382. for (var i = 0; i < parsedAction.properties.length; i++) {
  45383. var value = parsedAction.properties[i].value;
  45384. var name = parsedAction.properties[i].name;
  45385. var targetType = parsedAction.properties[i].targetType;
  45386. if (name === "target")
  45387. if (targetType !== null && targetType === "SceneProperties")
  45388. value = target = scene;
  45389. else
  45390. value = target = scene.getNodeByName(value);
  45391. else if (name === "parent")
  45392. value = scene.getNodeByName(value);
  45393. else if (name === "sound")
  45394. value = scene.getSoundByName(value);
  45395. else if (name !== "propertyPath") {
  45396. if (parsedAction.type === 2 && name === "operator")
  45397. value = BABYLON.ValueCondition[value];
  45398. else
  45399. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  45400. }
  45401. else {
  45402. propertyPath = value;
  45403. }
  45404. parameters.push(value);
  45405. }
  45406. }
  45407. if (combineArray === null) {
  45408. parameters.push(condition);
  45409. }
  45410. else {
  45411. parameters.push(null);
  45412. }
  45413. // If interpolate value action
  45414. if (parsedAction.name === "InterpolateValueAction") {
  45415. var param = parameters[parameters.length - 2];
  45416. parameters[parameters.length - 1] = param;
  45417. parameters[parameters.length - 2] = condition;
  45418. }
  45419. // Action or condition(s) and not CombineAction
  45420. var newAction = instanciate(parsedAction.name, parameters);
  45421. if (newAction instanceof BABYLON.Condition && condition !== null) {
  45422. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  45423. if (action)
  45424. action.then(nothing);
  45425. else
  45426. actionManager.registerAction(nothing);
  45427. action = nothing;
  45428. }
  45429. if (combineArray === null) {
  45430. if (newAction instanceof BABYLON.Condition) {
  45431. condition = newAction;
  45432. newAction = action;
  45433. }
  45434. else {
  45435. condition = null;
  45436. if (action)
  45437. action.then(newAction);
  45438. else
  45439. actionManager.registerAction(newAction);
  45440. }
  45441. }
  45442. else {
  45443. combineArray.push(newAction);
  45444. }
  45445. for (var i = 0; i < parsedAction.children.length; i++)
  45446. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45447. };
  45448. // triggers
  45449. for (var i = 0; i < parsedActions.children.length; i++) {
  45450. var triggerParams;
  45451. var trigger = parsedActions.children[i];
  45452. if (trigger.properties.length > 0) {
  45453. var param = trigger.properties[0].value;
  45454. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45455. if (value._meshId) {
  45456. value.mesh = scene.getMeshByID(value._meshId);
  45457. }
  45458. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45459. }
  45460. else
  45461. triggerParams = ActionManager[trigger.name];
  45462. for (var j = 0; j < trigger.children.length; j++) {
  45463. if (!trigger.detached)
  45464. traverse(trigger.children[j], triggerParams, null, null);
  45465. }
  45466. }
  45467. };
  45468. ActionManager.GetTriggerName = function (trigger) {
  45469. switch (trigger) {
  45470. case 0: return "NothingTrigger";
  45471. case 1: return "OnPickTrigger";
  45472. case 2: return "OnLeftPickTrigger";
  45473. case 3: return "OnRightPickTrigger";
  45474. case 4: return "OnCenterPickTrigger";
  45475. case 5: return "OnPickDownTrigger";
  45476. case 6: return "OnPickUpTrigger";
  45477. case 7: return "OnLongPressTrigger";
  45478. case 8: return "OnPointerOverTrigger";
  45479. case 9: return "OnPointerOutTrigger";
  45480. case 10: return "OnEveryFrameTrigger";
  45481. case 11: return "OnIntersectionEnterTrigger";
  45482. case 12: return "OnIntersectionExitTrigger";
  45483. case 13: return "OnKeyDownTrigger";
  45484. case 14: return "OnKeyUpTrigger";
  45485. case 15: return "OnPickOutTrigger";
  45486. default: return "";
  45487. }
  45488. };
  45489. // Statics
  45490. ActionManager._NothingTrigger = 0;
  45491. ActionManager._OnPickTrigger = 1;
  45492. ActionManager._OnLeftPickTrigger = 2;
  45493. ActionManager._OnRightPickTrigger = 3;
  45494. ActionManager._OnCenterPickTrigger = 4;
  45495. ActionManager._OnPickDownTrigger = 5;
  45496. ActionManager._OnDoublePickTrigger = 6;
  45497. ActionManager._OnPickUpTrigger = 7;
  45498. ActionManager._OnLongPressTrigger = 8;
  45499. ActionManager._OnPointerOverTrigger = 9;
  45500. ActionManager._OnPointerOutTrigger = 10;
  45501. ActionManager._OnEveryFrameTrigger = 11;
  45502. ActionManager._OnIntersectionEnterTrigger = 12;
  45503. ActionManager._OnIntersectionExitTrigger = 13;
  45504. ActionManager._OnKeyDownTrigger = 14;
  45505. ActionManager._OnKeyUpTrigger = 15;
  45506. ActionManager._OnPickOutTrigger = 16;
  45507. ActionManager.Triggers = {};
  45508. return ActionManager;
  45509. }());
  45510. BABYLON.ActionManager = ActionManager;
  45511. })(BABYLON || (BABYLON = {}));
  45512. //# sourceMappingURL=babylon.actionManager.js.map
  45513. var BABYLON;
  45514. (function (BABYLON) {
  45515. var InterpolateValueAction = /** @class */ (function (_super) {
  45516. __extends(InterpolateValueAction, _super);
  45517. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45518. if (duration === void 0) { duration = 1000; }
  45519. var _this = _super.call(this, triggerOptions, condition) || this;
  45520. _this.propertyPath = propertyPath;
  45521. _this.value = value;
  45522. _this.duration = duration;
  45523. _this.stopOtherAnimations = stopOtherAnimations;
  45524. _this.onInterpolationDone = onInterpolationDone;
  45525. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45526. _this._target = _this._effectiveTarget = target;
  45527. return _this;
  45528. }
  45529. InterpolateValueAction.prototype._prepare = function () {
  45530. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45531. this._property = this._getProperty(this.propertyPath);
  45532. };
  45533. InterpolateValueAction.prototype.execute = function () {
  45534. var _this = this;
  45535. var scene = this._actionManager.getScene();
  45536. var keys = [
  45537. {
  45538. frame: 0,
  45539. value: this._effectiveTarget[this._property]
  45540. }, {
  45541. frame: 100,
  45542. value: this.value
  45543. }
  45544. ];
  45545. var dataType;
  45546. if (typeof this.value === "number") {
  45547. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45548. }
  45549. else if (this.value instanceof BABYLON.Color3) {
  45550. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45551. }
  45552. else if (this.value instanceof BABYLON.Vector3) {
  45553. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45554. }
  45555. else if (this.value instanceof BABYLON.Matrix) {
  45556. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45557. }
  45558. else if (this.value instanceof BABYLON.Quaternion) {
  45559. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45560. }
  45561. else {
  45562. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45563. return;
  45564. }
  45565. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45566. animation.setKeys(keys);
  45567. if (this.stopOtherAnimations) {
  45568. scene.stopAnimation(this._effectiveTarget);
  45569. }
  45570. var wrapper = function () {
  45571. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45572. if (_this.onInterpolationDone) {
  45573. _this.onInterpolationDone();
  45574. }
  45575. };
  45576. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45577. };
  45578. InterpolateValueAction.prototype.serialize = function (parent) {
  45579. return _super.prototype._serialize.call(this, {
  45580. name: "InterpolateValueAction",
  45581. properties: [
  45582. BABYLON.Action._GetTargetProperty(this._target),
  45583. { name: "propertyPath", value: this.propertyPath },
  45584. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45585. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45586. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45587. ]
  45588. }, parent);
  45589. };
  45590. return InterpolateValueAction;
  45591. }(BABYLON.Action));
  45592. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45593. })(BABYLON || (BABYLON = {}));
  45594. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45595. var BABYLON;
  45596. (function (BABYLON) {
  45597. var SwitchBooleanAction = /** @class */ (function (_super) {
  45598. __extends(SwitchBooleanAction, _super);
  45599. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45600. var _this = _super.call(this, triggerOptions, condition) || this;
  45601. _this.propertyPath = propertyPath;
  45602. _this._target = _this._effectiveTarget = target;
  45603. return _this;
  45604. }
  45605. SwitchBooleanAction.prototype._prepare = function () {
  45606. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45607. this._property = this._getProperty(this.propertyPath);
  45608. };
  45609. SwitchBooleanAction.prototype.execute = function () {
  45610. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45611. };
  45612. SwitchBooleanAction.prototype.serialize = function (parent) {
  45613. return _super.prototype._serialize.call(this, {
  45614. name: "SwitchBooleanAction",
  45615. properties: [
  45616. BABYLON.Action._GetTargetProperty(this._target),
  45617. { name: "propertyPath", value: this.propertyPath }
  45618. ]
  45619. }, parent);
  45620. };
  45621. return SwitchBooleanAction;
  45622. }(BABYLON.Action));
  45623. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45624. var SetStateAction = /** @class */ (function (_super) {
  45625. __extends(SetStateAction, _super);
  45626. function SetStateAction(triggerOptions, target, value, condition) {
  45627. var _this = _super.call(this, triggerOptions, condition) || this;
  45628. _this.value = value;
  45629. _this._target = target;
  45630. return _this;
  45631. }
  45632. SetStateAction.prototype.execute = function () {
  45633. this._target.state = this.value;
  45634. };
  45635. SetStateAction.prototype.serialize = function (parent) {
  45636. return _super.prototype._serialize.call(this, {
  45637. name: "SetStateAction",
  45638. properties: [
  45639. BABYLON.Action._GetTargetProperty(this._target),
  45640. { name: "value", value: this.value }
  45641. ]
  45642. }, parent);
  45643. };
  45644. return SetStateAction;
  45645. }(BABYLON.Action));
  45646. BABYLON.SetStateAction = SetStateAction;
  45647. var SetValueAction = /** @class */ (function (_super) {
  45648. __extends(SetValueAction, _super);
  45649. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45650. var _this = _super.call(this, triggerOptions, condition) || this;
  45651. _this.propertyPath = propertyPath;
  45652. _this.value = value;
  45653. _this._target = _this._effectiveTarget = target;
  45654. return _this;
  45655. }
  45656. SetValueAction.prototype._prepare = function () {
  45657. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45658. this._property = this._getProperty(this.propertyPath);
  45659. };
  45660. SetValueAction.prototype.execute = function () {
  45661. this._effectiveTarget[this._property] = this.value;
  45662. if (this._target.markAsDirty) {
  45663. this._target.markAsDirty(this._property);
  45664. }
  45665. };
  45666. SetValueAction.prototype.serialize = function (parent) {
  45667. return _super.prototype._serialize.call(this, {
  45668. name: "SetValueAction",
  45669. properties: [
  45670. BABYLON.Action._GetTargetProperty(this._target),
  45671. { name: "propertyPath", value: this.propertyPath },
  45672. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45673. ]
  45674. }, parent);
  45675. };
  45676. return SetValueAction;
  45677. }(BABYLON.Action));
  45678. BABYLON.SetValueAction = SetValueAction;
  45679. var IncrementValueAction = /** @class */ (function (_super) {
  45680. __extends(IncrementValueAction, _super);
  45681. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45682. var _this = _super.call(this, triggerOptions, condition) || this;
  45683. _this.propertyPath = propertyPath;
  45684. _this.value = value;
  45685. _this._target = _this._effectiveTarget = target;
  45686. return _this;
  45687. }
  45688. IncrementValueAction.prototype._prepare = function () {
  45689. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45690. this._property = this._getProperty(this.propertyPath);
  45691. if (typeof this._effectiveTarget[this._property] !== "number") {
  45692. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45693. }
  45694. };
  45695. IncrementValueAction.prototype.execute = function () {
  45696. this._effectiveTarget[this._property] += this.value;
  45697. if (this._target.markAsDirty) {
  45698. this._target.markAsDirty(this._property);
  45699. }
  45700. };
  45701. IncrementValueAction.prototype.serialize = function (parent) {
  45702. return _super.prototype._serialize.call(this, {
  45703. name: "IncrementValueAction",
  45704. properties: [
  45705. BABYLON.Action._GetTargetProperty(this._target),
  45706. { name: "propertyPath", value: this.propertyPath },
  45707. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45708. ]
  45709. }, parent);
  45710. };
  45711. return IncrementValueAction;
  45712. }(BABYLON.Action));
  45713. BABYLON.IncrementValueAction = IncrementValueAction;
  45714. var PlayAnimationAction = /** @class */ (function (_super) {
  45715. __extends(PlayAnimationAction, _super);
  45716. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  45717. var _this = _super.call(this, triggerOptions, condition) || this;
  45718. _this.from = from;
  45719. _this.to = to;
  45720. _this.loop = loop;
  45721. _this._target = target;
  45722. return _this;
  45723. }
  45724. PlayAnimationAction.prototype._prepare = function () {
  45725. };
  45726. PlayAnimationAction.prototype.execute = function () {
  45727. var scene = this._actionManager.getScene();
  45728. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  45729. };
  45730. PlayAnimationAction.prototype.serialize = function (parent) {
  45731. return _super.prototype._serialize.call(this, {
  45732. name: "PlayAnimationAction",
  45733. properties: [
  45734. BABYLON.Action._GetTargetProperty(this._target),
  45735. { name: "from", value: String(this.from) },
  45736. { name: "to", value: String(this.to) },
  45737. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  45738. ]
  45739. }, parent);
  45740. };
  45741. return PlayAnimationAction;
  45742. }(BABYLON.Action));
  45743. BABYLON.PlayAnimationAction = PlayAnimationAction;
  45744. var StopAnimationAction = /** @class */ (function (_super) {
  45745. __extends(StopAnimationAction, _super);
  45746. function StopAnimationAction(triggerOptions, target, condition) {
  45747. var _this = _super.call(this, triggerOptions, condition) || this;
  45748. _this._target = target;
  45749. return _this;
  45750. }
  45751. StopAnimationAction.prototype._prepare = function () {
  45752. };
  45753. StopAnimationAction.prototype.execute = function () {
  45754. var scene = this._actionManager.getScene();
  45755. scene.stopAnimation(this._target);
  45756. };
  45757. StopAnimationAction.prototype.serialize = function (parent) {
  45758. return _super.prototype._serialize.call(this, {
  45759. name: "StopAnimationAction",
  45760. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  45761. }, parent);
  45762. };
  45763. return StopAnimationAction;
  45764. }(BABYLON.Action));
  45765. BABYLON.StopAnimationAction = StopAnimationAction;
  45766. var DoNothingAction = /** @class */ (function (_super) {
  45767. __extends(DoNothingAction, _super);
  45768. function DoNothingAction(triggerOptions, condition) {
  45769. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  45770. return _super.call(this, triggerOptions, condition) || this;
  45771. }
  45772. DoNothingAction.prototype.execute = function () {
  45773. };
  45774. DoNothingAction.prototype.serialize = function (parent) {
  45775. return _super.prototype._serialize.call(this, {
  45776. name: "DoNothingAction",
  45777. properties: []
  45778. }, parent);
  45779. };
  45780. return DoNothingAction;
  45781. }(BABYLON.Action));
  45782. BABYLON.DoNothingAction = DoNothingAction;
  45783. var CombineAction = /** @class */ (function (_super) {
  45784. __extends(CombineAction, _super);
  45785. function CombineAction(triggerOptions, children, condition) {
  45786. var _this = _super.call(this, triggerOptions, condition) || this;
  45787. _this.children = children;
  45788. return _this;
  45789. }
  45790. CombineAction.prototype._prepare = function () {
  45791. for (var index = 0; index < this.children.length; index++) {
  45792. this.children[index]._actionManager = this._actionManager;
  45793. this.children[index]._prepare();
  45794. }
  45795. };
  45796. CombineAction.prototype.execute = function (evt) {
  45797. for (var index = 0; index < this.children.length; index++) {
  45798. this.children[index].execute(evt);
  45799. }
  45800. };
  45801. CombineAction.prototype.serialize = function (parent) {
  45802. var serializationObject = _super.prototype._serialize.call(this, {
  45803. name: "CombineAction",
  45804. properties: [],
  45805. combine: []
  45806. }, parent);
  45807. for (var i = 0; i < this.children.length; i++) {
  45808. serializationObject.combine.push(this.children[i].serialize(null));
  45809. }
  45810. return serializationObject;
  45811. };
  45812. return CombineAction;
  45813. }(BABYLON.Action));
  45814. BABYLON.CombineAction = CombineAction;
  45815. var ExecuteCodeAction = /** @class */ (function (_super) {
  45816. __extends(ExecuteCodeAction, _super);
  45817. function ExecuteCodeAction(triggerOptions, func, condition) {
  45818. var _this = _super.call(this, triggerOptions, condition) || this;
  45819. _this.func = func;
  45820. return _this;
  45821. }
  45822. ExecuteCodeAction.prototype.execute = function (evt) {
  45823. this.func(evt);
  45824. };
  45825. return ExecuteCodeAction;
  45826. }(BABYLON.Action));
  45827. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  45828. var SetParentAction = /** @class */ (function (_super) {
  45829. __extends(SetParentAction, _super);
  45830. function SetParentAction(triggerOptions, target, parent, condition) {
  45831. var _this = _super.call(this, triggerOptions, condition) || this;
  45832. _this._target = target;
  45833. _this._parent = parent;
  45834. return _this;
  45835. }
  45836. SetParentAction.prototype._prepare = function () {
  45837. };
  45838. SetParentAction.prototype.execute = function () {
  45839. if (this._target.parent === this._parent) {
  45840. return;
  45841. }
  45842. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  45843. invertParentWorldMatrix.invert();
  45844. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  45845. this._target.parent = this._parent;
  45846. };
  45847. SetParentAction.prototype.serialize = function (parent) {
  45848. return _super.prototype._serialize.call(this, {
  45849. name: "SetParentAction",
  45850. properties: [
  45851. BABYLON.Action._GetTargetProperty(this._target),
  45852. BABYLON.Action._GetTargetProperty(this._parent),
  45853. ]
  45854. }, parent);
  45855. };
  45856. return SetParentAction;
  45857. }(BABYLON.Action));
  45858. BABYLON.SetParentAction = SetParentAction;
  45859. var PlaySoundAction = /** @class */ (function (_super) {
  45860. __extends(PlaySoundAction, _super);
  45861. function PlaySoundAction(triggerOptions, sound, condition) {
  45862. var _this = _super.call(this, triggerOptions, condition) || this;
  45863. _this._sound = sound;
  45864. return _this;
  45865. }
  45866. PlaySoundAction.prototype._prepare = function () {
  45867. };
  45868. PlaySoundAction.prototype.execute = function () {
  45869. if (this._sound !== undefined)
  45870. this._sound.play();
  45871. };
  45872. PlaySoundAction.prototype.serialize = function (parent) {
  45873. return _super.prototype._serialize.call(this, {
  45874. name: "PlaySoundAction",
  45875. properties: [{ name: "sound", value: this._sound.name }]
  45876. }, parent);
  45877. };
  45878. return PlaySoundAction;
  45879. }(BABYLON.Action));
  45880. BABYLON.PlaySoundAction = PlaySoundAction;
  45881. var StopSoundAction = /** @class */ (function (_super) {
  45882. __extends(StopSoundAction, _super);
  45883. function StopSoundAction(triggerOptions, sound, condition) {
  45884. var _this = _super.call(this, triggerOptions, condition) || this;
  45885. _this._sound = sound;
  45886. return _this;
  45887. }
  45888. StopSoundAction.prototype._prepare = function () {
  45889. };
  45890. StopSoundAction.prototype.execute = function () {
  45891. if (this._sound !== undefined)
  45892. this._sound.stop();
  45893. };
  45894. StopSoundAction.prototype.serialize = function (parent) {
  45895. return _super.prototype._serialize.call(this, {
  45896. name: "StopSoundAction",
  45897. properties: [{ name: "sound", value: this._sound.name }]
  45898. }, parent);
  45899. };
  45900. return StopSoundAction;
  45901. }(BABYLON.Action));
  45902. BABYLON.StopSoundAction = StopSoundAction;
  45903. })(BABYLON || (BABYLON = {}));
  45904. //# sourceMappingURL=babylon.directActions.js.map
  45905. var BABYLON;
  45906. (function (BABYLON) {
  45907. var SpriteManager = /** @class */ (function () {
  45908. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  45909. if (epsilon === void 0) { epsilon = 0.01; }
  45910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45911. this.name = name;
  45912. this.sprites = new Array();
  45913. this.renderingGroupId = 0;
  45914. this.layerMask = 0x0FFFFFFF;
  45915. this.fogEnabled = true;
  45916. this.isPickable = false;
  45917. /**
  45918. * An event triggered when the manager is disposed.
  45919. * @type {BABYLON.Observable}
  45920. */
  45921. this.onDisposeObservable = new BABYLON.Observable();
  45922. this._vertexBuffers = {};
  45923. this._capacity = capacity;
  45924. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  45925. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45926. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45927. if (cellSize.width && cellSize.height) {
  45928. this.cellWidth = cellSize.width;
  45929. this.cellHeight = cellSize.height;
  45930. }
  45931. else if (cellSize !== undefined) {
  45932. this.cellWidth = cellSize;
  45933. this.cellHeight = cellSize;
  45934. }
  45935. else {
  45936. return;
  45937. }
  45938. this._epsilon = epsilon;
  45939. this._scene = scene;
  45940. this._scene.spriteManagers.push(this);
  45941. var indices = [];
  45942. var index = 0;
  45943. for (var count = 0; count < capacity; count++) {
  45944. indices.push(index);
  45945. indices.push(index + 1);
  45946. indices.push(index + 2);
  45947. indices.push(index);
  45948. indices.push(index + 2);
  45949. indices.push(index + 3);
  45950. index += 4;
  45951. }
  45952. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  45953. // VBO
  45954. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  45955. this._vertexData = new Float32Array(capacity * 16 * 4);
  45956. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  45957. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  45958. var options = this._buffer.createVertexBuffer("options", 4, 4);
  45959. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  45960. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  45961. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45962. this._vertexBuffers["options"] = options;
  45963. this._vertexBuffers["cellInfo"] = cellInfo;
  45964. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45965. // Effects
  45966. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  45967. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  45968. }
  45969. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  45970. set: function (callback) {
  45971. if (this._onDisposeObserver) {
  45972. this.onDisposeObservable.remove(this._onDisposeObserver);
  45973. }
  45974. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45975. },
  45976. enumerable: true,
  45977. configurable: true
  45978. });
  45979. Object.defineProperty(SpriteManager.prototype, "texture", {
  45980. get: function () {
  45981. return this._spriteTexture;
  45982. },
  45983. set: function (value) {
  45984. this._spriteTexture = value;
  45985. },
  45986. enumerable: true,
  45987. configurable: true
  45988. });
  45989. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  45990. var arrayOffset = index * 16;
  45991. if (offsetX === 0)
  45992. offsetX = this._epsilon;
  45993. else if (offsetX === 1)
  45994. offsetX = 1 - this._epsilon;
  45995. if (offsetY === 0)
  45996. offsetY = this._epsilon;
  45997. else if (offsetY === 1)
  45998. offsetY = 1 - this._epsilon;
  45999. this._vertexData[arrayOffset] = sprite.position.x;
  46000. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46001. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46002. this._vertexData[arrayOffset + 3] = sprite.angle;
  46003. this._vertexData[arrayOffset + 4] = sprite.width;
  46004. this._vertexData[arrayOffset + 5] = sprite.height;
  46005. this._vertexData[arrayOffset + 6] = offsetX;
  46006. this._vertexData[arrayOffset + 7] = offsetY;
  46007. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46008. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46009. var offset = (sprite.cellIndex / rowSize) >> 0;
  46010. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46011. this._vertexData[arrayOffset + 11] = offset;
  46012. // Color
  46013. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46014. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46015. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46016. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46017. };
  46018. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46019. var count = Math.min(this._capacity, this.sprites.length);
  46020. var min = BABYLON.Vector3.Zero();
  46021. var max = BABYLON.Vector3.Zero();
  46022. var distance = Number.MAX_VALUE;
  46023. var currentSprite = null;
  46024. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46025. var cameraView = camera.getViewMatrix();
  46026. for (var index = 0; index < count; index++) {
  46027. var sprite = this.sprites[index];
  46028. if (!sprite) {
  46029. continue;
  46030. }
  46031. if (predicate) {
  46032. if (!predicate(sprite)) {
  46033. continue;
  46034. }
  46035. }
  46036. else if (!sprite.isPickable) {
  46037. continue;
  46038. }
  46039. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46040. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46041. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46042. if (ray.intersectsBoxMinMax(min, max)) {
  46043. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46044. if (distance > currentDistance) {
  46045. distance = currentDistance;
  46046. currentSprite = sprite;
  46047. if (fastCheck) {
  46048. break;
  46049. }
  46050. }
  46051. }
  46052. }
  46053. if (currentSprite) {
  46054. var result = new BABYLON.PickingInfo();
  46055. result.hit = true;
  46056. result.pickedSprite = currentSprite;
  46057. result.distance = distance;
  46058. return result;
  46059. }
  46060. return null;
  46061. };
  46062. SpriteManager.prototype.render = function () {
  46063. // Check
  46064. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46065. return;
  46066. var engine = this._scene.getEngine();
  46067. var baseSize = this._spriteTexture.getBaseSize();
  46068. // Sprites
  46069. var deltaTime = engine.getDeltaTime();
  46070. var max = Math.min(this._capacity, this.sprites.length);
  46071. var rowSize = baseSize.width / this.cellWidth;
  46072. var offset = 0;
  46073. for (var index = 0; index < max; index++) {
  46074. var sprite = this.sprites[index];
  46075. if (!sprite) {
  46076. continue;
  46077. }
  46078. sprite._animate(deltaTime);
  46079. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46080. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46081. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46082. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46083. }
  46084. this._buffer.update(this._vertexData);
  46085. // Render
  46086. var effect = this._effectBase;
  46087. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46088. effect = this._effectFog;
  46089. }
  46090. engine.enableEffect(effect);
  46091. var viewMatrix = this._scene.getViewMatrix();
  46092. effect.setTexture("diffuseSampler", this._spriteTexture);
  46093. effect.setMatrix("view", viewMatrix);
  46094. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46095. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46096. // Fog
  46097. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46098. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46099. effect.setColor3("vFogColor", this._scene.fogColor);
  46100. }
  46101. // VBOs
  46102. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46103. // Draw order
  46104. engine.setDepthFunctionToLessOrEqual();
  46105. effect.setBool("alphaTest", true);
  46106. engine.setColorWrite(false);
  46107. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46108. engine.setColorWrite(true);
  46109. effect.setBool("alphaTest", false);
  46110. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46111. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46112. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46113. };
  46114. SpriteManager.prototype.dispose = function () {
  46115. if (this._buffer) {
  46116. this._buffer.dispose();
  46117. this._buffer = null;
  46118. }
  46119. if (this._indexBuffer) {
  46120. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46121. this._indexBuffer = null;
  46122. }
  46123. if (this._spriteTexture) {
  46124. this._spriteTexture.dispose();
  46125. this._spriteTexture = null;
  46126. }
  46127. // Remove from scene
  46128. var index = this._scene.spriteManagers.indexOf(this);
  46129. this._scene.spriteManagers.splice(index, 1);
  46130. // Callback
  46131. this.onDisposeObservable.notifyObservers(this);
  46132. this.onDisposeObservable.clear();
  46133. };
  46134. return SpriteManager;
  46135. }());
  46136. BABYLON.SpriteManager = SpriteManager;
  46137. })(BABYLON || (BABYLON = {}));
  46138. //# sourceMappingURL=babylon.spriteManager.js.map
  46139. var BABYLON;
  46140. (function (BABYLON) {
  46141. var Sprite = /** @class */ (function () {
  46142. function Sprite(name, manager) {
  46143. this.name = name;
  46144. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46145. this.width = 1.0;
  46146. this.height = 1.0;
  46147. this.angle = 0;
  46148. this.cellIndex = 0;
  46149. this.invertU = 0;
  46150. this.invertV = 0;
  46151. this.animations = new Array();
  46152. this.isPickable = false;
  46153. this._animationStarted = false;
  46154. this._loopAnimation = false;
  46155. this._fromIndex = 0;
  46156. this._toIndex = 0;
  46157. this._delay = 0;
  46158. this._direction = 1;
  46159. this._time = 0;
  46160. this._manager = manager;
  46161. this._manager.sprites.push(this);
  46162. this.position = BABYLON.Vector3.Zero();
  46163. }
  46164. Object.defineProperty(Sprite.prototype, "size", {
  46165. get: function () {
  46166. return this.width;
  46167. },
  46168. set: function (value) {
  46169. this.width = value;
  46170. this.height = value;
  46171. },
  46172. enumerable: true,
  46173. configurable: true
  46174. });
  46175. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46176. this._fromIndex = from;
  46177. this._toIndex = to;
  46178. this._loopAnimation = loop;
  46179. this._delay = delay;
  46180. this._animationStarted = true;
  46181. this._direction = from < to ? 1 : -1;
  46182. this.cellIndex = from;
  46183. this._time = 0;
  46184. this._onAnimationEnd = onAnimationEnd;
  46185. };
  46186. Sprite.prototype.stopAnimation = function () {
  46187. this._animationStarted = false;
  46188. };
  46189. Sprite.prototype._animate = function (deltaTime) {
  46190. if (!this._animationStarted)
  46191. return;
  46192. this._time += deltaTime;
  46193. if (this._time > this._delay) {
  46194. this._time = this._time % this._delay;
  46195. this.cellIndex += this._direction;
  46196. if (this.cellIndex > this._toIndex) {
  46197. if (this._loopAnimation) {
  46198. this.cellIndex = this._fromIndex;
  46199. }
  46200. else {
  46201. this.cellIndex = this._toIndex;
  46202. this._animationStarted = false;
  46203. if (this._onAnimationEnd) {
  46204. this._onAnimationEnd();
  46205. }
  46206. if (this.disposeWhenFinishedAnimating) {
  46207. this.dispose();
  46208. }
  46209. }
  46210. }
  46211. }
  46212. };
  46213. Sprite.prototype.dispose = function () {
  46214. for (var i = 0; i < this._manager.sprites.length; i++) {
  46215. if (this._manager.sprites[i] == this) {
  46216. this._manager.sprites.splice(i, 1);
  46217. }
  46218. }
  46219. };
  46220. return Sprite;
  46221. }());
  46222. BABYLON.Sprite = Sprite;
  46223. })(BABYLON || (BABYLON = {}));
  46224. //# sourceMappingURL=babylon.sprite.js.map
  46225. var BABYLON;
  46226. (function (BABYLON) {
  46227. var IntersectionInfo = /** @class */ (function () {
  46228. function IntersectionInfo(bu, bv, distance) {
  46229. this.bu = bu;
  46230. this.bv = bv;
  46231. this.distance = distance;
  46232. this.faceId = 0;
  46233. this.subMeshId = 0;
  46234. }
  46235. return IntersectionInfo;
  46236. }());
  46237. BABYLON.IntersectionInfo = IntersectionInfo;
  46238. var PickingInfo = /** @class */ (function () {
  46239. function PickingInfo() {
  46240. this.hit = false;
  46241. this.distance = 0;
  46242. this.pickedPoint = null;
  46243. this.pickedMesh = null;
  46244. this.bu = 0;
  46245. this.bv = 0;
  46246. this.faceId = -1;
  46247. this.subMeshId = 0;
  46248. this.pickedSprite = null;
  46249. }
  46250. // Methods
  46251. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  46252. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  46253. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  46254. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46255. return null;
  46256. }
  46257. var indices = this.pickedMesh.getIndices();
  46258. if (!indices) {
  46259. return null;
  46260. }
  46261. var result;
  46262. if (useVerticesNormals) {
  46263. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46264. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  46265. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  46266. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  46267. normal0 = normal0.scale(this.bu);
  46268. normal1 = normal1.scale(this.bv);
  46269. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  46270. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  46271. }
  46272. else {
  46273. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46274. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  46275. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  46276. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  46277. var p1p2 = vertex1.subtract(vertex2);
  46278. var p3p2 = vertex3.subtract(vertex2);
  46279. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  46280. }
  46281. if (useWorldCoordinates) {
  46282. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  46283. }
  46284. return BABYLON.Vector3.Normalize(result);
  46285. };
  46286. PickingInfo.prototype.getTextureCoordinates = function () {
  46287. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46288. return null;
  46289. }
  46290. var indices = this.pickedMesh.getIndices();
  46291. if (!indices) {
  46292. return null;
  46293. }
  46294. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46295. if (!uvs) {
  46296. return null;
  46297. }
  46298. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  46299. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  46300. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  46301. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  46302. uv1 = uv1.scale(this.bu);
  46303. uv2 = uv2.scale(this.bv);
  46304. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  46305. };
  46306. return PickingInfo;
  46307. }());
  46308. BABYLON.PickingInfo = PickingInfo;
  46309. })(BABYLON || (BABYLON = {}));
  46310. //# sourceMappingURL=babylon.pickingInfo.js.map
  46311. var BABYLON;
  46312. (function (BABYLON) {
  46313. var Ray = /** @class */ (function () {
  46314. function Ray(origin, direction, length) {
  46315. if (length === void 0) { length = Number.MAX_VALUE; }
  46316. this.origin = origin;
  46317. this.direction = direction;
  46318. this.length = length;
  46319. }
  46320. // Methods
  46321. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  46322. var d = 0.0;
  46323. var maxValue = Number.MAX_VALUE;
  46324. var inv;
  46325. var min;
  46326. var max;
  46327. var temp;
  46328. if (Math.abs(this.direction.x) < 0.0000001) {
  46329. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  46330. return false;
  46331. }
  46332. }
  46333. else {
  46334. inv = 1.0 / this.direction.x;
  46335. min = (minimum.x - this.origin.x) * inv;
  46336. max = (maximum.x - this.origin.x) * inv;
  46337. if (max === -Infinity) {
  46338. max = Infinity;
  46339. }
  46340. if (min > max) {
  46341. temp = min;
  46342. min = max;
  46343. max = temp;
  46344. }
  46345. d = Math.max(min, d);
  46346. maxValue = Math.min(max, maxValue);
  46347. if (d > maxValue) {
  46348. return false;
  46349. }
  46350. }
  46351. if (Math.abs(this.direction.y) < 0.0000001) {
  46352. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  46353. return false;
  46354. }
  46355. }
  46356. else {
  46357. inv = 1.0 / this.direction.y;
  46358. min = (minimum.y - this.origin.y) * inv;
  46359. max = (maximum.y - this.origin.y) * inv;
  46360. if (max === -Infinity) {
  46361. max = Infinity;
  46362. }
  46363. if (min > max) {
  46364. temp = min;
  46365. min = max;
  46366. max = temp;
  46367. }
  46368. d = Math.max(min, d);
  46369. maxValue = Math.min(max, maxValue);
  46370. if (d > maxValue) {
  46371. return false;
  46372. }
  46373. }
  46374. if (Math.abs(this.direction.z) < 0.0000001) {
  46375. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  46376. return false;
  46377. }
  46378. }
  46379. else {
  46380. inv = 1.0 / this.direction.z;
  46381. min = (minimum.z - this.origin.z) * inv;
  46382. max = (maximum.z - this.origin.z) * inv;
  46383. if (max === -Infinity) {
  46384. max = Infinity;
  46385. }
  46386. if (min > max) {
  46387. temp = min;
  46388. min = max;
  46389. max = temp;
  46390. }
  46391. d = Math.max(min, d);
  46392. maxValue = Math.min(max, maxValue);
  46393. if (d > maxValue) {
  46394. return false;
  46395. }
  46396. }
  46397. return true;
  46398. };
  46399. Ray.prototype.intersectsBox = function (box) {
  46400. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  46401. };
  46402. Ray.prototype.intersectsSphere = function (sphere) {
  46403. var x = sphere.center.x - this.origin.x;
  46404. var y = sphere.center.y - this.origin.y;
  46405. var z = sphere.center.z - this.origin.z;
  46406. var pyth = (x * x) + (y * y) + (z * z);
  46407. var rr = sphere.radius * sphere.radius;
  46408. if (pyth <= rr) {
  46409. return true;
  46410. }
  46411. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  46412. if (dot < 0.0) {
  46413. return false;
  46414. }
  46415. var temp = pyth - (dot * dot);
  46416. return temp <= rr;
  46417. };
  46418. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  46419. if (!this._edge1) {
  46420. this._edge1 = BABYLON.Vector3.Zero();
  46421. this._edge2 = BABYLON.Vector3.Zero();
  46422. this._pvec = BABYLON.Vector3.Zero();
  46423. this._tvec = BABYLON.Vector3.Zero();
  46424. this._qvec = BABYLON.Vector3.Zero();
  46425. }
  46426. vertex1.subtractToRef(vertex0, this._edge1);
  46427. vertex2.subtractToRef(vertex0, this._edge2);
  46428. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46429. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46430. if (det === 0) {
  46431. return null;
  46432. }
  46433. var invdet = 1 / det;
  46434. this.origin.subtractToRef(vertex0, this._tvec);
  46435. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46436. if (bu < 0 || bu > 1.0) {
  46437. return null;
  46438. }
  46439. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46440. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46441. if (bv < 0 || bu + bv > 1.0) {
  46442. return null;
  46443. }
  46444. //check if the distance is longer than the predefined length.
  46445. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46446. if (distance > this.length) {
  46447. return null;
  46448. }
  46449. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46450. };
  46451. Ray.prototype.intersectsPlane = function (plane) {
  46452. var distance;
  46453. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46454. if (Math.abs(result1) < 9.99999997475243E-07) {
  46455. return null;
  46456. }
  46457. else {
  46458. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46459. distance = (-plane.d - result2) / result1;
  46460. if (distance < 0.0) {
  46461. if (distance < -9.99999997475243E-07) {
  46462. return null;
  46463. }
  46464. else {
  46465. return 0;
  46466. }
  46467. }
  46468. return distance;
  46469. }
  46470. };
  46471. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46472. var tm = BABYLON.Tmp.Matrix[0];
  46473. mesh.getWorldMatrix().invertToRef(tm);
  46474. if (this._tmpRay) {
  46475. Ray.TransformToRef(this, tm, this._tmpRay);
  46476. }
  46477. else {
  46478. this._tmpRay = Ray.Transform(this, tm);
  46479. }
  46480. return mesh.intersects(this._tmpRay, fastCheck);
  46481. };
  46482. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46483. if (results) {
  46484. results.length = 0;
  46485. }
  46486. else {
  46487. results = [];
  46488. }
  46489. for (var i = 0; i < meshes.length; i++) {
  46490. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46491. if (pickInfo.hit) {
  46492. results.push(pickInfo);
  46493. }
  46494. }
  46495. results.sort(this._comparePickingInfo);
  46496. return results;
  46497. };
  46498. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46499. if (pickingInfoA.distance < pickingInfoB.distance) {
  46500. return -1;
  46501. }
  46502. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46503. return 1;
  46504. }
  46505. else {
  46506. return 0;
  46507. }
  46508. };
  46509. /**
  46510. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46511. * @param sega the first point of the segment to test the intersection against
  46512. * @param segb the second point of the segment to test the intersection against
  46513. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46514. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46515. */
  46516. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46517. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46518. var u = segb.subtract(sega);
  46519. var v = rsegb.subtract(this.origin);
  46520. var w = sega.subtract(this.origin);
  46521. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46522. var b = BABYLON.Vector3.Dot(u, v);
  46523. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46524. var d = BABYLON.Vector3.Dot(u, w);
  46525. var e = BABYLON.Vector3.Dot(v, w);
  46526. var D = a * c - b * b; // always >= 0
  46527. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46528. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46529. // compute the line parameters of the two closest points
  46530. if (D < Ray.smallnum) {
  46531. sN = 0.0; // force using point P0 on segment S1
  46532. sD = 1.0; // to prevent possible division by 0.0 later
  46533. tN = e;
  46534. tD = c;
  46535. }
  46536. else {
  46537. sN = (b * e - c * d);
  46538. tN = (a * e - b * d);
  46539. if (sN < 0.0) {
  46540. sN = 0.0;
  46541. tN = e;
  46542. tD = c;
  46543. }
  46544. else if (sN > sD) {
  46545. sN = sD;
  46546. tN = e + b;
  46547. tD = c;
  46548. }
  46549. }
  46550. if (tN < 0.0) {
  46551. tN = 0.0;
  46552. // recompute sc for this edge
  46553. if (-d < 0.0) {
  46554. sN = 0.0;
  46555. }
  46556. else if (-d > a)
  46557. sN = sD;
  46558. else {
  46559. sN = -d;
  46560. sD = a;
  46561. }
  46562. }
  46563. else if (tN > tD) {
  46564. tN = tD;
  46565. // recompute sc for this edge
  46566. if ((-d + b) < 0.0) {
  46567. sN = 0;
  46568. }
  46569. else if ((-d + b) > a) {
  46570. sN = sD;
  46571. }
  46572. else {
  46573. sN = (-d + b);
  46574. sD = a;
  46575. }
  46576. }
  46577. // finally do the division to get sc and tc
  46578. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46579. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46580. // get the difference of the two closest points
  46581. var qtc = v.multiplyByFloats(tc, tc, tc);
  46582. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46583. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46584. if (isIntersected) {
  46585. return qtc.length();
  46586. }
  46587. return -1;
  46588. };
  46589. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46590. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46591. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46592. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46593. this.direction.normalize();
  46594. return this;
  46595. };
  46596. // Statics
  46597. Ray.Zero = function () {
  46598. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46599. };
  46600. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46601. var result = Ray.Zero();
  46602. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46603. };
  46604. /**
  46605. * 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
  46606. * transformed to the given world matrix.
  46607. * @param origin The origin point
  46608. * @param end The end point
  46609. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46610. */
  46611. Ray.CreateNewFromTo = function (origin, end, world) {
  46612. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46613. var direction = end.subtract(origin);
  46614. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46615. direction.normalize();
  46616. return Ray.Transform(new Ray(origin, direction, length), world);
  46617. };
  46618. Ray.Transform = function (ray, matrix) {
  46619. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46620. Ray.TransformToRef(ray, matrix, result);
  46621. return result;
  46622. };
  46623. Ray.TransformToRef = function (ray, matrix, result) {
  46624. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46625. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46626. result.length = ray.length;
  46627. var dir = result.direction;
  46628. var len = dir.length();
  46629. if (!(len === 0 || len === 1)) {
  46630. var num = 1.0 / len;
  46631. dir.x *= num;
  46632. dir.y *= num;
  46633. dir.z *= num;
  46634. result.length *= len;
  46635. }
  46636. };
  46637. Ray.smallnum = 0.00000001;
  46638. Ray.rayl = 10e8;
  46639. return Ray;
  46640. }());
  46641. BABYLON.Ray = Ray;
  46642. })(BABYLON || (BABYLON = {}));
  46643. //# sourceMappingURL=babylon.ray.js.map
  46644. var BABYLON;
  46645. (function (BABYLON) {
  46646. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46647. if (boxMin.x > sphereCenter.x + sphereRadius)
  46648. return false;
  46649. if (sphereCenter.x - sphereRadius > boxMax.x)
  46650. return false;
  46651. if (boxMin.y > sphereCenter.y + sphereRadius)
  46652. return false;
  46653. if (sphereCenter.y - sphereRadius > boxMax.y)
  46654. return false;
  46655. if (boxMin.z > sphereCenter.z + sphereRadius)
  46656. return false;
  46657. if (sphereCenter.z - sphereRadius > boxMax.z)
  46658. return false;
  46659. return true;
  46660. };
  46661. var getLowestRoot = (function () {
  46662. var result = { root: 0, found: false };
  46663. return function (a, b, c, maxR) {
  46664. result.root = 0;
  46665. result.found = false;
  46666. var determinant = b * b - 4.0 * a * c;
  46667. if (determinant < 0)
  46668. return result;
  46669. var sqrtD = Math.sqrt(determinant);
  46670. var r1 = (-b - sqrtD) / (2.0 * a);
  46671. var r2 = (-b + sqrtD) / (2.0 * a);
  46672. if (r1 > r2) {
  46673. var temp = r2;
  46674. r2 = r1;
  46675. r1 = temp;
  46676. }
  46677. if (r1 > 0 && r1 < maxR) {
  46678. result.root = r1;
  46679. result.found = true;
  46680. return result;
  46681. }
  46682. if (r2 > 0 && r2 < maxR) {
  46683. result.root = r2;
  46684. result.found = true;
  46685. return result;
  46686. }
  46687. return result;
  46688. };
  46689. })();
  46690. var Collider = /** @class */ (function () {
  46691. function Collider() {
  46692. this._collisionPoint = BABYLON.Vector3.Zero();
  46693. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  46694. this._tempVector = BABYLON.Vector3.Zero();
  46695. this._tempVector2 = BABYLON.Vector3.Zero();
  46696. this._tempVector3 = BABYLON.Vector3.Zero();
  46697. this._tempVector4 = BABYLON.Vector3.Zero();
  46698. this._edge = BABYLON.Vector3.Zero();
  46699. this._baseToVertex = BABYLON.Vector3.Zero();
  46700. this._destinationPoint = BABYLON.Vector3.Zero();
  46701. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  46702. this._displacementVector = BABYLON.Vector3.Zero();
  46703. this._radius = BABYLON.Vector3.One();
  46704. this._retry = 0;
  46705. this._basePointWorld = BABYLON.Vector3.Zero();
  46706. this._velocityWorld = BABYLON.Vector3.Zero();
  46707. this._normalizedVelocity = BABYLON.Vector3.Zero();
  46708. this._collisionMask = -1;
  46709. }
  46710. Object.defineProperty(Collider.prototype, "collisionMask", {
  46711. get: function () {
  46712. return this._collisionMask;
  46713. },
  46714. set: function (mask) {
  46715. this._collisionMask = !isNaN(mask) ? mask : -1;
  46716. },
  46717. enumerable: true,
  46718. configurable: true
  46719. });
  46720. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  46721. /**
  46722. * Gets the plane normal used to compute the sliding response (in local space)
  46723. */
  46724. get: function () {
  46725. return this._slidePlaneNormal;
  46726. },
  46727. enumerable: true,
  46728. configurable: true
  46729. });
  46730. // Methods
  46731. Collider.prototype._initialize = function (source, dir, e) {
  46732. this._velocity = dir;
  46733. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  46734. this._basePoint = source;
  46735. source.multiplyToRef(this._radius, this._basePointWorld);
  46736. dir.multiplyToRef(this._radius, this._velocityWorld);
  46737. this._velocityWorldLength = this._velocityWorld.length();
  46738. this._epsilon = e;
  46739. this.collisionFound = false;
  46740. };
  46741. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  46742. pa.subtractToRef(point, this._tempVector);
  46743. pb.subtractToRef(point, this._tempVector2);
  46744. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  46745. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46746. if (d < 0)
  46747. return false;
  46748. pc.subtractToRef(point, this._tempVector3);
  46749. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  46750. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46751. if (d < 0)
  46752. return false;
  46753. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  46754. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46755. return d >= 0;
  46756. };
  46757. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  46758. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  46759. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  46760. if (distance > this._velocityWorldLength + max + sphereRadius) {
  46761. return false;
  46762. }
  46763. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  46764. return false;
  46765. return true;
  46766. };
  46767. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  46768. var t0;
  46769. var embeddedInPlane = false;
  46770. //defensive programming, actually not needed.
  46771. if (!trianglePlaneArray) {
  46772. trianglePlaneArray = [];
  46773. }
  46774. if (!trianglePlaneArray[faceIndex]) {
  46775. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  46776. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  46777. }
  46778. var trianglePlane = trianglePlaneArray[faceIndex];
  46779. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  46780. return;
  46781. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  46782. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  46783. if (normalDotVelocity == 0) {
  46784. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  46785. return;
  46786. embeddedInPlane = true;
  46787. t0 = 0;
  46788. }
  46789. else {
  46790. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46791. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46792. if (t0 > t1) {
  46793. var temp = t1;
  46794. t1 = t0;
  46795. t0 = temp;
  46796. }
  46797. if (t0 > 1.0 || t1 < 0.0)
  46798. return;
  46799. if (t0 < 0)
  46800. t0 = 0;
  46801. if (t0 > 1.0)
  46802. t0 = 1.0;
  46803. }
  46804. this._collisionPoint.copyFromFloats(0, 0, 0);
  46805. var found = false;
  46806. var t = 1.0;
  46807. if (!embeddedInPlane) {
  46808. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  46809. this._velocity.scaleToRef(t0, this._tempVector);
  46810. this._planeIntersectionPoint.addInPlace(this._tempVector);
  46811. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  46812. found = true;
  46813. t = t0;
  46814. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  46815. }
  46816. }
  46817. if (!found) {
  46818. var velocitySquaredLength = this._velocity.lengthSquared();
  46819. var a = velocitySquaredLength;
  46820. this._basePoint.subtractToRef(p1, this._tempVector);
  46821. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46822. var c = this._tempVector.lengthSquared() - 1.0;
  46823. var lowestRoot = getLowestRoot(a, b, c, t);
  46824. if (lowestRoot.found) {
  46825. t = lowestRoot.root;
  46826. found = true;
  46827. this._collisionPoint.copyFrom(p1);
  46828. }
  46829. this._basePoint.subtractToRef(p2, this._tempVector);
  46830. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46831. c = this._tempVector.lengthSquared() - 1.0;
  46832. lowestRoot = getLowestRoot(a, b, c, t);
  46833. if (lowestRoot.found) {
  46834. t = lowestRoot.root;
  46835. found = true;
  46836. this._collisionPoint.copyFrom(p2);
  46837. }
  46838. this._basePoint.subtractToRef(p3, this._tempVector);
  46839. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46840. c = this._tempVector.lengthSquared() - 1.0;
  46841. lowestRoot = getLowestRoot(a, b, c, t);
  46842. if (lowestRoot.found) {
  46843. t = lowestRoot.root;
  46844. found = true;
  46845. this._collisionPoint.copyFrom(p3);
  46846. }
  46847. p2.subtractToRef(p1, this._edge);
  46848. p1.subtractToRef(this._basePoint, this._baseToVertex);
  46849. var edgeSquaredLength = this._edge.lengthSquared();
  46850. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46851. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46852. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46853. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46854. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46855. lowestRoot = getLowestRoot(a, b, c, t);
  46856. if (lowestRoot.found) {
  46857. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46858. if (f >= 0.0 && f <= 1.0) {
  46859. t = lowestRoot.root;
  46860. found = true;
  46861. this._edge.scaleInPlace(f);
  46862. p1.addToRef(this._edge, this._collisionPoint);
  46863. }
  46864. }
  46865. p3.subtractToRef(p2, this._edge);
  46866. p2.subtractToRef(this._basePoint, this._baseToVertex);
  46867. edgeSquaredLength = this._edge.lengthSquared();
  46868. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46869. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46870. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46871. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46872. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46873. lowestRoot = getLowestRoot(a, b, c, t);
  46874. if (lowestRoot.found) {
  46875. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46876. if (f >= 0.0 && f <= 1.0) {
  46877. t = lowestRoot.root;
  46878. found = true;
  46879. this._edge.scaleInPlace(f);
  46880. p2.addToRef(this._edge, this._collisionPoint);
  46881. }
  46882. }
  46883. p1.subtractToRef(p3, this._edge);
  46884. p3.subtractToRef(this._basePoint, this._baseToVertex);
  46885. edgeSquaredLength = this._edge.lengthSquared();
  46886. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46887. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46888. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46889. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46890. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46891. lowestRoot = getLowestRoot(a, b, c, t);
  46892. if (lowestRoot.found) {
  46893. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46894. if (f >= 0.0 && f <= 1.0) {
  46895. t = lowestRoot.root;
  46896. found = true;
  46897. this._edge.scaleInPlace(f);
  46898. p3.addToRef(this._edge, this._collisionPoint);
  46899. }
  46900. }
  46901. }
  46902. if (found) {
  46903. var distToCollision = t * this._velocity.length();
  46904. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  46905. if (!this.intersectionPoint) {
  46906. this.intersectionPoint = this._collisionPoint.clone();
  46907. }
  46908. else {
  46909. this.intersectionPoint.copyFrom(this._collisionPoint);
  46910. }
  46911. this._nearestDistance = distToCollision;
  46912. this.collisionFound = true;
  46913. }
  46914. }
  46915. };
  46916. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  46917. for (var i = indexStart; i < indexEnd; i += 3) {
  46918. var p1 = pts[indices[i] - decal];
  46919. var p2 = pts[indices[i + 1] - decal];
  46920. var p3 = pts[indices[i + 2] - decal];
  46921. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  46922. }
  46923. };
  46924. Collider.prototype._getResponse = function (pos, vel) {
  46925. pos.addToRef(vel, this._destinationPoint);
  46926. vel.scaleInPlace((this._nearestDistance / vel.length()));
  46927. this._basePoint.addToRef(vel, pos);
  46928. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  46929. this._slidePlaneNormal.normalize();
  46930. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  46931. pos.addInPlace(this._displacementVector);
  46932. this.intersectionPoint.addInPlace(this._displacementVector);
  46933. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  46934. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  46935. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  46936. };
  46937. return Collider;
  46938. }());
  46939. BABYLON.Collider = Collider;
  46940. })(BABYLON || (BABYLON = {}));
  46941. //# sourceMappingURL=babylon.collider.js.map
  46942. var BABYLON;
  46943. (function (BABYLON) {
  46944. //WebWorker code will be inserted to this variable.
  46945. BABYLON.CollisionWorker = "";
  46946. var WorkerTaskType;
  46947. (function (WorkerTaskType) {
  46948. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  46949. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  46950. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  46951. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  46952. var WorkerReplyType;
  46953. (function (WorkerReplyType) {
  46954. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  46955. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  46956. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  46957. var CollisionCoordinatorWorker = /** @class */ (function () {
  46958. function CollisionCoordinatorWorker() {
  46959. var _this = this;
  46960. this._scaledPosition = BABYLON.Vector3.Zero();
  46961. this._scaledVelocity = BABYLON.Vector3.Zero();
  46962. this.onMeshUpdated = function (transformNode) {
  46963. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  46964. };
  46965. this.onGeometryUpdated = function (geometry) {
  46966. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  46967. };
  46968. this._afterRender = function () {
  46969. if (!_this._init)
  46970. return;
  46971. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  46972. return;
  46973. }
  46974. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  46975. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  46976. if (_this._runningUpdated > 4) {
  46977. return;
  46978. }
  46979. ++_this._runningUpdated;
  46980. var payload = {
  46981. updatedMeshes: _this._addUpdateMeshesList,
  46982. updatedGeometries: _this._addUpdateGeometriesList,
  46983. removedGeometries: _this._toRemoveGeometryArray,
  46984. removedMeshes: _this._toRemoveMeshesArray
  46985. };
  46986. var message = {
  46987. payload: payload,
  46988. taskType: WorkerTaskType.UPDATE
  46989. };
  46990. var serializable = [];
  46991. for (var id in payload.updatedGeometries) {
  46992. if (payload.updatedGeometries.hasOwnProperty(id)) {
  46993. //prepare transferables
  46994. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  46995. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  46996. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  46997. }
  46998. }
  46999. _this._worker.postMessage(message, serializable);
  47000. _this._addUpdateMeshesList = {};
  47001. _this._addUpdateGeometriesList = {};
  47002. _this._toRemoveGeometryArray = [];
  47003. _this._toRemoveMeshesArray = [];
  47004. };
  47005. this._onMessageFromWorker = function (e) {
  47006. var returnData = e.data;
  47007. if (returnData.error != WorkerReplyType.SUCCESS) {
  47008. //TODO what errors can be returned from the worker?
  47009. BABYLON.Tools.Warn("error returned from worker!");
  47010. return;
  47011. }
  47012. switch (returnData.taskType) {
  47013. case WorkerTaskType.INIT:
  47014. _this._init = true;
  47015. //Update the worked with ALL of the scene's current state
  47016. _this._scene.meshes.forEach(function (mesh) {
  47017. _this.onMeshAdded(mesh);
  47018. });
  47019. _this._scene.getGeometries().forEach(function (geometry) {
  47020. _this.onGeometryAdded(geometry);
  47021. });
  47022. break;
  47023. case WorkerTaskType.UPDATE:
  47024. _this._runningUpdated--;
  47025. break;
  47026. case WorkerTaskType.COLLIDE:
  47027. var returnPayload = returnData.payload;
  47028. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47029. return;
  47030. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47031. if (callback) {
  47032. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47033. if (mesh) {
  47034. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47035. }
  47036. }
  47037. //cleanup
  47038. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47039. break;
  47040. }
  47041. };
  47042. this._collisionsCallbackArray = [];
  47043. this._init = false;
  47044. this._runningUpdated = 0;
  47045. this._addUpdateMeshesList = {};
  47046. this._addUpdateGeometriesList = {};
  47047. this._toRemoveGeometryArray = [];
  47048. this._toRemoveMeshesArray = [];
  47049. }
  47050. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47051. if (!this._init)
  47052. return;
  47053. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47054. return;
  47055. position.divideToRef(collider._radius, this._scaledPosition);
  47056. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47057. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47058. var payload = {
  47059. collider: {
  47060. position: this._scaledPosition.asArray(),
  47061. velocity: this._scaledVelocity.asArray(),
  47062. radius: collider._radius.asArray()
  47063. },
  47064. collisionId: collisionIndex,
  47065. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47066. maximumRetry: maximumRetry
  47067. };
  47068. var message = {
  47069. payload: payload,
  47070. taskType: WorkerTaskType.COLLIDE
  47071. };
  47072. this._worker.postMessage(message);
  47073. };
  47074. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47075. this._scene = scene;
  47076. this._scene.registerAfterRender(this._afterRender);
  47077. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47078. this._worker = new Worker(workerUrl);
  47079. this._worker.onmessage = this._onMessageFromWorker;
  47080. var message = {
  47081. payload: {},
  47082. taskType: WorkerTaskType.INIT
  47083. };
  47084. this._worker.postMessage(message);
  47085. };
  47086. CollisionCoordinatorWorker.prototype.destroy = function () {
  47087. this._scene.unregisterAfterRender(this._afterRender);
  47088. this._worker.terminate();
  47089. };
  47090. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47091. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47092. this.onMeshUpdated(mesh);
  47093. };
  47094. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47095. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47096. };
  47097. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47098. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47099. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47100. this.onGeometryUpdated(geometry);
  47101. };
  47102. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47103. this._toRemoveGeometryArray.push(geometry.id);
  47104. };
  47105. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47106. var submeshes = [];
  47107. if (mesh.subMeshes) {
  47108. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47109. var boundingInfo = sm.getBoundingInfo();
  47110. return {
  47111. position: idx,
  47112. verticesStart: sm.verticesStart,
  47113. verticesCount: sm.verticesCount,
  47114. indexStart: sm.indexStart,
  47115. indexCount: sm.indexCount,
  47116. hasMaterial: !!sm.getMaterial(),
  47117. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47118. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47119. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47120. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47121. };
  47122. });
  47123. }
  47124. var geometryId = null;
  47125. if (mesh instanceof BABYLON.Mesh) {
  47126. var geometry = mesh.geometry;
  47127. geometryId = geometry ? geometry.id : null;
  47128. }
  47129. else if (mesh instanceof BABYLON.InstancedMesh) {
  47130. var geometry = mesh.sourceMesh.geometry;
  47131. geometryId = geometry ? geometry.id : null;
  47132. }
  47133. var boundingInfo = mesh.getBoundingInfo();
  47134. return {
  47135. uniqueId: mesh.uniqueId,
  47136. id: mesh.id,
  47137. name: mesh.name,
  47138. geometryId: geometryId,
  47139. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47140. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47141. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47142. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47143. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47144. subMeshes: submeshes,
  47145. checkCollisions: mesh.checkCollisions
  47146. };
  47147. };
  47148. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47149. return {
  47150. id: geometry.id,
  47151. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47152. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47153. indices: new Uint32Array(geometry.getIndices() || []),
  47154. };
  47155. };
  47156. return CollisionCoordinatorWorker;
  47157. }());
  47158. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47159. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47160. function CollisionCoordinatorLegacy() {
  47161. this._scaledPosition = BABYLON.Vector3.Zero();
  47162. this._scaledVelocity = BABYLON.Vector3.Zero();
  47163. this._finalPosition = BABYLON.Vector3.Zero();
  47164. }
  47165. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47166. position.divideToRef(collider._radius, this._scaledPosition);
  47167. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47168. collider.collidedMesh = null;
  47169. collider._retry = 0;
  47170. collider._initialVelocity = this._scaledVelocity;
  47171. collider._initialPosition = this._scaledPosition;
  47172. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47173. this._finalPosition.multiplyInPlace(collider._radius);
  47174. //run the callback
  47175. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47176. };
  47177. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47178. this._scene = scene;
  47179. };
  47180. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47181. //Legacy need no destruction method.
  47182. };
  47183. //No update in legacy mode
  47184. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  47185. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  47186. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  47187. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  47188. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  47189. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  47190. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  47191. if (excludedMesh === void 0) { excludedMesh = null; }
  47192. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  47193. if (collider._retry >= maximumRetry) {
  47194. finalPosition.copyFrom(position);
  47195. return;
  47196. }
  47197. // Check if this is a mesh else camera or -1
  47198. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  47199. collider._initialize(position, velocity, closeDistance);
  47200. // Check all meshes
  47201. for (var index = 0; index < this._scene.meshes.length; index++) {
  47202. var mesh = this._scene.meshes[index];
  47203. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  47204. mesh._checkCollision(collider);
  47205. }
  47206. }
  47207. if (!collider.collisionFound) {
  47208. position.addToRef(velocity, finalPosition);
  47209. return;
  47210. }
  47211. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  47212. collider._getResponse(position, velocity);
  47213. }
  47214. if (velocity.length() <= closeDistance) {
  47215. finalPosition.copyFrom(position);
  47216. return;
  47217. }
  47218. collider._retry++;
  47219. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  47220. };
  47221. return CollisionCoordinatorLegacy;
  47222. }());
  47223. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  47224. })(BABYLON || (BABYLON = {}));
  47225. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  47226. var BABYLON;
  47227. (function (BABYLON) {
  47228. /**
  47229. * A particle represents one of the element emitted by a particle system.
  47230. * This is mainly define by its coordinates, direction, velocity and age.
  47231. */
  47232. var Particle = /** @class */ (function () {
  47233. /**
  47234. * Creates a new instance of @see Particle
  47235. * @param particleSystem the particle system the particle belongs to
  47236. */
  47237. function Particle(particleSystem) {
  47238. this.particleSystem = particleSystem;
  47239. /**
  47240. * The world position of the particle in the scene.
  47241. */
  47242. this.position = BABYLON.Vector3.Zero();
  47243. /**
  47244. * The world direction of the particle in the scene.
  47245. */
  47246. this.direction = BABYLON.Vector3.Zero();
  47247. /**
  47248. * The color of the particle.
  47249. */
  47250. this.color = new BABYLON.Color4(0, 0, 0, 0);
  47251. /**
  47252. * The color change of the particle per step.
  47253. */
  47254. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  47255. /**
  47256. * Defines how long will the life of the particle be.
  47257. */
  47258. this.lifeTime = 1.0;
  47259. /**
  47260. * The current age of the particle.
  47261. */
  47262. this.age = 0;
  47263. /**
  47264. * The current size of the particle.
  47265. */
  47266. this.size = 0;
  47267. /**
  47268. * The current angle of the particle.
  47269. */
  47270. this.angle = 0;
  47271. /**
  47272. * Defines how fast is the angle changing.
  47273. */
  47274. this.angularSpeed = 0;
  47275. /**
  47276. * Defines the cell index used by the particle to be rendered from a sprite.
  47277. */
  47278. this.cellIndex = 0;
  47279. this._currentFrameCounter = 0;
  47280. if (!this.particleSystem.isAnimationSheetEnabled) {
  47281. return;
  47282. }
  47283. this.cellIndex = this.particleSystem.startSpriteCellID;
  47284. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  47285. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  47286. }
  47287. else {
  47288. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  47289. }
  47290. }
  47291. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  47292. // (ageOffset / scaledUpdateSpeed) / available cells
  47293. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  47294. this._currentFrameCounter += scaledUpdateSpeed;
  47295. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  47296. this._currentFrameCounter = 0;
  47297. this.cellIndex++;
  47298. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47299. this.cellIndex = this.particleSystem.endSpriteCellID;
  47300. }
  47301. }
  47302. };
  47303. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  47304. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  47305. this.cellIndex++;
  47306. this._currentFrameCounter = 0;
  47307. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47308. if (this.particleSystem.spriteCellLoop) {
  47309. this.cellIndex = this.particleSystem.startSpriteCellID;
  47310. }
  47311. else {
  47312. this.cellIndex = this.particleSystem.endSpriteCellID;
  47313. }
  47314. }
  47315. }
  47316. else {
  47317. this._currentFrameCounter++;
  47318. }
  47319. };
  47320. /**
  47321. * Copy the properties of particle to another one.
  47322. * @param other the particle to copy the information to.
  47323. */
  47324. Particle.prototype.copyTo = function (other) {
  47325. other.position.copyFrom(this.position);
  47326. other.direction.copyFrom(this.direction);
  47327. other.color.copyFrom(this.color);
  47328. other.colorStep.copyFrom(this.colorStep);
  47329. other.lifeTime = this.lifeTime;
  47330. other.age = this.age;
  47331. other.size = this.size;
  47332. other.angle = this.angle;
  47333. other.angularSpeed = this.angularSpeed;
  47334. other.particleSystem = this.particleSystem;
  47335. other.cellIndex = this.cellIndex;
  47336. };
  47337. return Particle;
  47338. }());
  47339. BABYLON.Particle = Particle;
  47340. })(BABYLON || (BABYLON = {}));
  47341. //# sourceMappingURL=babylon.particle.js.map
  47342. var BABYLON;
  47343. (function (BABYLON) {
  47344. /**
  47345. * This represents a particle system in Babylon.
  47346. * 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.
  47347. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  47348. * @example https://doc.babylonjs.com/babylon101/particles
  47349. */
  47350. var ParticleSystem = /** @class */ (function () {
  47351. /**
  47352. * Instantiates a particle system.
  47353. * 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.
  47354. * @param name The name of the particle system
  47355. * @param capacity The max number of particles alive at the same time
  47356. * @param scene The scene the particle system belongs to
  47357. * @param customEffect a custom effect used to change the way particles are rendered by default
  47358. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  47359. * @param epsilon Offset used to render the particles
  47360. */
  47361. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  47362. if (customEffect === void 0) { customEffect = null; }
  47363. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  47364. if (epsilon === void 0) { epsilon = 0.01; }
  47365. var _this = this;
  47366. /**
  47367. * List of animations used by the particle system.
  47368. */
  47369. this.animations = [];
  47370. /**
  47371. * The rendering group used by the Particle system to chose when to render.
  47372. */
  47373. this.renderingGroupId = 0;
  47374. /**
  47375. * The emitter represents the Mesh or position we are attaching the particle system to.
  47376. */
  47377. this.emitter = null;
  47378. /**
  47379. * The density of particles, the rate of particle flow
  47380. */
  47381. this.emitRate = 10;
  47382. /**
  47383. * If you want to launch only a few particles at once, that can be done, as well.
  47384. */
  47385. this.manualEmitCount = -1;
  47386. /**
  47387. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47388. */
  47389. this.updateSpeed = 0.01;
  47390. /**
  47391. * The amount of time the particle system is running (depends of the overall speed above).
  47392. */
  47393. this.targetStopDuration = 0;
  47394. /**
  47395. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  47396. */
  47397. this.disposeOnStop = false;
  47398. /**
  47399. * Minimum power of emitting particles.
  47400. */
  47401. this.minEmitPower = 1;
  47402. /**
  47403. * Maximum power of emitting particles.
  47404. */
  47405. this.maxEmitPower = 1;
  47406. /**
  47407. * Minimum life time of emitting particles.
  47408. */
  47409. this.minLifeTime = 1;
  47410. /**
  47411. * Maximum life time of emitting particles.
  47412. */
  47413. this.maxLifeTime = 1;
  47414. /**
  47415. * Minimum Size of emitting particles.
  47416. */
  47417. this.minSize = 1;
  47418. /**
  47419. * Maximum Size of emitting particles.
  47420. */
  47421. this.maxSize = 1;
  47422. /**
  47423. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  47424. */
  47425. this.minAngularSpeed = 0;
  47426. /**
  47427. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  47428. */
  47429. this.maxAngularSpeed = 0;
  47430. /**
  47431. * The layer mask we are rendering the particles through.
  47432. */
  47433. this.layerMask = 0x0FFFFFFF;
  47434. /**
  47435. * This can help using your own shader to render the particle system.
  47436. * The according effect will be created
  47437. */
  47438. this.customShader = null;
  47439. /**
  47440. * By default particle system starts as soon as they are created. This prevents the
  47441. * automatic start to happen and let you decide when to start emitting particles.
  47442. */
  47443. this.preventAutoStart = false;
  47444. /**
  47445. * Callback triggered when the particle animation is ending.
  47446. */
  47447. this.onAnimationEnd = null;
  47448. /**
  47449. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47450. */
  47451. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47452. /**
  47453. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47454. * to override the particles.
  47455. */
  47456. this.forceDepthWrite = false;
  47457. /**
  47458. * You can use gravity if you want to give an orientation to your particles.
  47459. */
  47460. this.gravity = BABYLON.Vector3.Zero();
  47461. /**
  47462. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47463. */
  47464. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47465. /**
  47466. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47467. */
  47468. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47469. /**
  47470. * 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.
  47471. */
  47472. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47473. /**
  47474. * 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.
  47475. */
  47476. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47477. /**
  47478. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47479. */
  47480. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47481. /**
  47482. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47483. */
  47484. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47485. /**
  47486. * Color the particle will have at the end of its lifetime.
  47487. */
  47488. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47489. /**
  47490. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47491. */
  47492. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47493. /**
  47494. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47495. */
  47496. this.spriteCellLoop = true;
  47497. /**
  47498. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47499. */
  47500. this.spriteCellChangeSpeed = 0;
  47501. /**
  47502. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47503. */
  47504. this.startSpriteCellID = 0;
  47505. /**
  47506. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47507. */
  47508. this.endSpriteCellID = 0;
  47509. /**
  47510. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47511. */
  47512. this.spriteCellWidth = 0;
  47513. /**
  47514. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47515. */
  47516. this.spriteCellHeight = 0;
  47517. /**
  47518. * An event triggered when the system is disposed.
  47519. */
  47520. this.onDisposeObservable = new BABYLON.Observable();
  47521. this._particles = new Array();
  47522. this._stockParticles = new Array();
  47523. this._newPartsExcess = 0;
  47524. this._vertexBuffers = {};
  47525. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47526. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47527. this._scaledDirection = BABYLON.Vector3.Zero();
  47528. this._scaledGravity = BABYLON.Vector3.Zero();
  47529. this._currentRenderId = -1;
  47530. this._started = false;
  47531. this._stopped = false;
  47532. this._actualFrame = 0;
  47533. this._vertexBufferSize = 11;
  47534. this._appendParticleVertexes = null;
  47535. this.id = name;
  47536. this.name = name;
  47537. this._capacity = capacity;
  47538. this._epsilon = epsilon;
  47539. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47540. if (isAnimationSheetEnabled) {
  47541. this._vertexBufferSize = 12;
  47542. }
  47543. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47544. this._customEffect = customEffect;
  47545. scene.particleSystems.push(this);
  47546. this._createIndexBuffer();
  47547. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47548. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47549. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47550. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47551. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47552. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47553. if (this._isAnimationSheetEnabled) {
  47554. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47555. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47556. }
  47557. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47558. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47559. this._vertexBuffers["options"] = options;
  47560. // Default behaviors
  47561. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47562. this.updateFunction = function (particles) {
  47563. for (var index = 0; index < particles.length; index++) {
  47564. var particle = particles[index];
  47565. particle.age += _this._scaledUpdateSpeed;
  47566. if (particle.age >= particle.lifeTime) {
  47567. _this.recycleParticle(particle);
  47568. index--;
  47569. continue;
  47570. }
  47571. else {
  47572. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47573. particle.color.addInPlace(_this._scaledColorStep);
  47574. if (particle.color.a < 0)
  47575. particle.color.a = 0;
  47576. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47577. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47578. particle.position.addInPlace(_this._scaledDirection);
  47579. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47580. particle.direction.addInPlace(_this._scaledGravity);
  47581. if (_this._isAnimationSheetEnabled) {
  47582. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47583. }
  47584. }
  47585. }
  47586. };
  47587. }
  47588. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47589. /**
  47590. * Sets a callback that will be triggered when the system is disposed.
  47591. */
  47592. set: function (callback) {
  47593. if (this._onDisposeObserver) {
  47594. this.onDisposeObservable.remove(this._onDisposeObserver);
  47595. }
  47596. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47597. },
  47598. enumerable: true,
  47599. configurable: true
  47600. });
  47601. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47602. /**
  47603. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47604. */
  47605. get: function () {
  47606. return this._isAnimationSheetEnabled;
  47607. },
  47608. enumerable: true,
  47609. configurable: true
  47610. });
  47611. ParticleSystem.prototype._createIndexBuffer = function () {
  47612. var indices = [];
  47613. var index = 0;
  47614. for (var count = 0; count < this._capacity; count++) {
  47615. indices.push(index);
  47616. indices.push(index + 1);
  47617. indices.push(index + 2);
  47618. indices.push(index);
  47619. indices.push(index + 2);
  47620. indices.push(index + 3);
  47621. index += 4;
  47622. }
  47623. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47624. };
  47625. /**
  47626. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47627. * Its lifetime will start back at 0.
  47628. * @param particle The particle to recycle
  47629. */
  47630. ParticleSystem.prototype.recycleParticle = function (particle) {
  47631. var lastParticle = this._particles.pop();
  47632. if (lastParticle !== particle) {
  47633. lastParticle.copyTo(particle);
  47634. this._stockParticles.push(lastParticle);
  47635. }
  47636. };
  47637. /**
  47638. * Gets the maximum number of particles active at the same time.
  47639. * @returns The max number of active particles.
  47640. */
  47641. ParticleSystem.prototype.getCapacity = function () {
  47642. return this._capacity;
  47643. };
  47644. /**
  47645. * Gets Wether there are still active particles in the system.
  47646. * @returns True if it is alive, otherwise false.
  47647. */
  47648. ParticleSystem.prototype.isAlive = function () {
  47649. return this._alive;
  47650. };
  47651. /**
  47652. * Gets Wether the system has been started.
  47653. * @returns True if it has been started, otherwise false.
  47654. */
  47655. ParticleSystem.prototype.isStarted = function () {
  47656. return this._started;
  47657. };
  47658. /**
  47659. * Starts the particle system and begins to emit.
  47660. */
  47661. ParticleSystem.prototype.start = function () {
  47662. this._started = true;
  47663. this._stopped = false;
  47664. this._actualFrame = 0;
  47665. };
  47666. /**
  47667. * Stops the particle system.
  47668. */
  47669. ParticleSystem.prototype.stop = function () {
  47670. this._stopped = true;
  47671. };
  47672. /**
  47673. * @ignore (for internal use only)
  47674. */
  47675. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47676. var offset = index * this._vertexBufferSize;
  47677. this._vertexData[offset] = particle.position.x;
  47678. this._vertexData[offset + 1] = particle.position.y;
  47679. this._vertexData[offset + 2] = particle.position.z;
  47680. this._vertexData[offset + 3] = particle.color.r;
  47681. this._vertexData[offset + 4] = particle.color.g;
  47682. this._vertexData[offset + 5] = particle.color.b;
  47683. this._vertexData[offset + 6] = particle.color.a;
  47684. this._vertexData[offset + 7] = particle.angle;
  47685. this._vertexData[offset + 8] = particle.size;
  47686. this._vertexData[offset + 9] = offsetX;
  47687. this._vertexData[offset + 10] = offsetY;
  47688. };
  47689. /**
  47690. * @ignore (for internal use only)
  47691. */
  47692. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  47693. if (offsetX === 0)
  47694. offsetX = this._epsilon;
  47695. else if (offsetX === 1)
  47696. offsetX = 1 - this._epsilon;
  47697. if (offsetY === 0)
  47698. offsetY = this._epsilon;
  47699. else if (offsetY === 1)
  47700. offsetY = 1 - this._epsilon;
  47701. var offset = index * this._vertexBufferSize;
  47702. this._vertexData[offset] = particle.position.x;
  47703. this._vertexData[offset + 1] = particle.position.y;
  47704. this._vertexData[offset + 2] = particle.position.z;
  47705. this._vertexData[offset + 3] = particle.color.r;
  47706. this._vertexData[offset + 4] = particle.color.g;
  47707. this._vertexData[offset + 5] = particle.color.b;
  47708. this._vertexData[offset + 6] = particle.color.a;
  47709. this._vertexData[offset + 7] = particle.angle;
  47710. this._vertexData[offset + 8] = particle.size;
  47711. this._vertexData[offset + 9] = offsetX;
  47712. this._vertexData[offset + 10] = offsetY;
  47713. this._vertexData[offset + 11] = particle.cellIndex;
  47714. };
  47715. ParticleSystem.prototype._update = function (newParticles) {
  47716. // Update current
  47717. this._alive = this._particles.length > 0;
  47718. this.updateFunction(this._particles);
  47719. // Add new ones
  47720. var worldMatrix;
  47721. if (this.emitter.position) {
  47722. var emitterMesh = this.emitter;
  47723. worldMatrix = emitterMesh.getWorldMatrix();
  47724. }
  47725. else {
  47726. var emitterPosition = this.emitter;
  47727. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  47728. }
  47729. var particle;
  47730. for (var index = 0; index < newParticles; index++) {
  47731. if (this._particles.length === this._capacity) {
  47732. break;
  47733. }
  47734. if (this._stockParticles.length !== 0) {
  47735. particle = this._stockParticles.pop();
  47736. particle.age = 0;
  47737. particle.cellIndex = this.startSpriteCellID;
  47738. }
  47739. else {
  47740. particle = new BABYLON.Particle(this);
  47741. }
  47742. this._particles.push(particle);
  47743. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  47744. if (this.startPositionFunction) {
  47745. this.startPositionFunction(worldMatrix, particle.position, particle);
  47746. }
  47747. else {
  47748. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  47749. }
  47750. if (this.startDirectionFunction) {
  47751. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47752. }
  47753. else {
  47754. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47755. }
  47756. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  47757. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  47758. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  47759. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  47760. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  47761. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  47762. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  47763. }
  47764. };
  47765. ParticleSystem.prototype._getEffect = function () {
  47766. if (this._customEffect) {
  47767. return this._customEffect;
  47768. }
  47769. ;
  47770. var defines = [];
  47771. if (this._scene.clipPlane) {
  47772. defines.push("#define CLIPPLANE");
  47773. }
  47774. if (this._isAnimationSheetEnabled) {
  47775. defines.push("#define ANIMATESHEET");
  47776. }
  47777. // Effect
  47778. var join = defines.join("\n");
  47779. if (this._cachedDefines !== join) {
  47780. this._cachedDefines = join;
  47781. var attributesNamesOrOptions;
  47782. var effectCreationOption;
  47783. if (this._isAnimationSheetEnabled) {
  47784. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  47785. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  47786. }
  47787. else {
  47788. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  47789. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  47790. }
  47791. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  47792. }
  47793. return this._effect;
  47794. };
  47795. /**
  47796. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  47797. */
  47798. ParticleSystem.prototype.animate = function () {
  47799. if (!this._started)
  47800. return;
  47801. var effect = this._getEffect();
  47802. // Check
  47803. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  47804. return;
  47805. if (this._currentRenderId === this._scene.getRenderId()) {
  47806. return;
  47807. }
  47808. this._currentRenderId = this._scene.getRenderId();
  47809. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  47810. // determine the number of particles we need to create
  47811. var newParticles;
  47812. if (this.manualEmitCount > -1) {
  47813. newParticles = this.manualEmitCount;
  47814. this._newPartsExcess = 0;
  47815. this.manualEmitCount = 0;
  47816. }
  47817. else {
  47818. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  47819. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  47820. }
  47821. if (this._newPartsExcess > 1.0) {
  47822. newParticles += this._newPartsExcess >> 0;
  47823. this._newPartsExcess -= this._newPartsExcess >> 0;
  47824. }
  47825. this._alive = false;
  47826. if (!this._stopped) {
  47827. this._actualFrame += this._scaledUpdateSpeed;
  47828. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  47829. this.stop();
  47830. }
  47831. else {
  47832. newParticles = 0;
  47833. }
  47834. this._update(newParticles);
  47835. // Stopped?
  47836. if (this._stopped) {
  47837. if (!this._alive) {
  47838. this._started = false;
  47839. if (this.onAnimationEnd) {
  47840. this.onAnimationEnd();
  47841. }
  47842. if (this.disposeOnStop) {
  47843. this._scene._toBeDisposed.push(this);
  47844. }
  47845. }
  47846. }
  47847. // Animation sheet
  47848. if (this._isAnimationSheetEnabled) {
  47849. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  47850. }
  47851. else {
  47852. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  47853. }
  47854. // Update VBO
  47855. var offset = 0;
  47856. for (var index = 0; index < this._particles.length; index++) {
  47857. var particle = this._particles[index];
  47858. this._appendParticleVertexes(offset, particle);
  47859. offset += 4;
  47860. }
  47861. if (this._vertexBuffer) {
  47862. this._vertexBuffer.update(this._vertexData);
  47863. }
  47864. };
  47865. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  47866. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  47867. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  47868. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  47869. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  47870. };
  47871. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  47872. this._appendParticleVertex(offset++, particle, 0, 0);
  47873. this._appendParticleVertex(offset++, particle, 1, 0);
  47874. this._appendParticleVertex(offset++, particle, 1, 1);
  47875. this._appendParticleVertex(offset++, particle, 0, 1);
  47876. };
  47877. /**
  47878. * Rebuilds the particle system.
  47879. */
  47880. ParticleSystem.prototype.rebuild = function () {
  47881. this._createIndexBuffer();
  47882. if (this._vertexBuffer) {
  47883. this._vertexBuffer._rebuild();
  47884. }
  47885. };
  47886. /**
  47887. * Renders the particle system in its current state.
  47888. * @returns the current number of particles.
  47889. */
  47890. ParticleSystem.prototype.render = function () {
  47891. var effect = this._getEffect();
  47892. // Check
  47893. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  47894. return 0;
  47895. var engine = this._scene.getEngine();
  47896. // Render
  47897. engine.enableEffect(effect);
  47898. engine.setState(false);
  47899. var viewMatrix = this._scene.getViewMatrix();
  47900. effect.setTexture("diffuseSampler", this.particleTexture);
  47901. effect.setMatrix("view", viewMatrix);
  47902. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47903. if (this._isAnimationSheetEnabled) {
  47904. var baseSize = this.particleTexture.getBaseSize();
  47905. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  47906. }
  47907. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  47908. if (this._scene.clipPlane) {
  47909. var clipPlane = this._scene.clipPlane;
  47910. var invView = viewMatrix.clone();
  47911. invView.invert();
  47912. effect.setMatrix("invView", invView);
  47913. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  47914. }
  47915. // VBOs
  47916. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47917. // Draw order
  47918. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  47919. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  47920. }
  47921. else {
  47922. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47923. }
  47924. if (this.forceDepthWrite) {
  47925. engine.setDepthWrite(true);
  47926. }
  47927. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  47928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47929. return this._particles.length;
  47930. };
  47931. /**
  47932. * Disposes the particle system and free the associated resources.
  47933. */
  47934. ParticleSystem.prototype.dispose = function () {
  47935. if (this._vertexBuffer) {
  47936. this._vertexBuffer.dispose();
  47937. this._vertexBuffer = null;
  47938. }
  47939. if (this._indexBuffer) {
  47940. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47941. this._indexBuffer = null;
  47942. }
  47943. if (this.particleTexture) {
  47944. this.particleTexture.dispose();
  47945. this.particleTexture = null;
  47946. }
  47947. // Remove from scene
  47948. var index = this._scene.particleSystems.indexOf(this);
  47949. if (index > -1) {
  47950. this._scene.particleSystems.splice(index, 1);
  47951. }
  47952. // Callback
  47953. this.onDisposeObservable.notifyObservers(this);
  47954. this.onDisposeObservable.clear();
  47955. };
  47956. /**
  47957. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  47958. * @param radius The radius of the sphere to emit from
  47959. * @returns the emitter
  47960. */
  47961. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  47962. if (radius === void 0) { radius = 1; }
  47963. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  47964. this.particleEmitterType = particleEmitter;
  47965. return particleEmitter;
  47966. };
  47967. /**
  47968. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  47969. * @param radius The radius of the sphere to emit from
  47970. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  47971. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  47972. * @returns the emitter
  47973. */
  47974. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  47975. if (radius === void 0) { radius = 1; }
  47976. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  47977. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  47978. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  47979. this.particleEmitterType = particleEmitter;
  47980. return particleEmitter;
  47981. };
  47982. /**
  47983. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  47984. * @param radius The radius of the cone to emit from
  47985. * @param angle The base angle of the cone
  47986. * @returns the emitter
  47987. */
  47988. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  47989. if (radius === void 0) { radius = 1; }
  47990. if (angle === void 0) { angle = Math.PI / 4; }
  47991. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  47992. this.particleEmitterType = particleEmitter;
  47993. return particleEmitter;
  47994. };
  47995. // 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.
  47996. /**
  47997. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  47998. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  47999. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48000. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48001. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48002. * @returns the emitter
  48003. */
  48004. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48005. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48006. this.direction1 = direction1;
  48007. this.direction2 = direction2;
  48008. this.minEmitBox = minEmitBox;
  48009. this.maxEmitBox = maxEmitBox;
  48010. this.particleEmitterType = particleEmitter;
  48011. return particleEmitter;
  48012. };
  48013. /**
  48014. * Clones the particle system.
  48015. * @param name The name of the cloned object
  48016. * @param newEmitter The new emitter to use
  48017. * @returns the cloned particle system
  48018. */
  48019. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48020. var custom = null;
  48021. var program = null;
  48022. if (this.customShader != null) {
  48023. program = this.customShader;
  48024. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48025. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48026. }
  48027. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48028. result.customShader = program;
  48029. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48030. if (newEmitter === undefined) {
  48031. newEmitter = this.emitter;
  48032. }
  48033. result.emitter = newEmitter;
  48034. if (this.particleTexture) {
  48035. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48036. }
  48037. if (!this.preventAutoStart) {
  48038. result.start();
  48039. }
  48040. return result;
  48041. };
  48042. /**
  48043. * Serializes the particle system to a JSON object.
  48044. * @returns the JSON object
  48045. */
  48046. ParticleSystem.prototype.serialize = function () {
  48047. var serializationObject = {};
  48048. serializationObject.name = this.name;
  48049. serializationObject.id = this.id;
  48050. // Emitter
  48051. if (this.emitter.position) {
  48052. var emitterMesh = this.emitter;
  48053. serializationObject.emitterId = emitterMesh.id;
  48054. }
  48055. else {
  48056. var emitterPosition = this.emitter;
  48057. serializationObject.emitter = emitterPosition.asArray();
  48058. }
  48059. serializationObject.capacity = this.getCapacity();
  48060. if (this.particleTexture) {
  48061. serializationObject.textureName = this.particleTexture.name;
  48062. }
  48063. // Animations
  48064. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48065. // Particle system
  48066. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48067. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48068. serializationObject.minSize = this.minSize;
  48069. serializationObject.maxSize = this.maxSize;
  48070. serializationObject.minEmitPower = this.minEmitPower;
  48071. serializationObject.maxEmitPower = this.maxEmitPower;
  48072. serializationObject.minLifeTime = this.minLifeTime;
  48073. serializationObject.maxLifeTime = this.maxLifeTime;
  48074. serializationObject.emitRate = this.emitRate;
  48075. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48076. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48077. serializationObject.gravity = this.gravity.asArray();
  48078. serializationObject.direction1 = this.direction1.asArray();
  48079. serializationObject.direction2 = this.direction2.asArray();
  48080. serializationObject.color1 = this.color1.asArray();
  48081. serializationObject.color2 = this.color2.asArray();
  48082. serializationObject.colorDead = this.colorDead.asArray();
  48083. serializationObject.updateSpeed = this.updateSpeed;
  48084. serializationObject.targetStopDuration = this.targetStopDuration;
  48085. serializationObject.textureMask = this.textureMask.asArray();
  48086. serializationObject.blendMode = this.blendMode;
  48087. serializationObject.customShader = this.customShader;
  48088. serializationObject.preventAutoStart = this.preventAutoStart;
  48089. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48090. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48091. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48092. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48093. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48094. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48095. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48096. return serializationObject;
  48097. };
  48098. /**
  48099. * Parses a JSON object to create a particle system.
  48100. * @param parsedParticleSystem The JSON object to parse
  48101. * @param scene The scene to create the particle system in
  48102. * @param rootUrl The root url to use to load external dependencies like texture
  48103. * @returns the Parsed particle system
  48104. */
  48105. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48106. var name = parsedParticleSystem.name;
  48107. var custom = null;
  48108. var program = null;
  48109. if (parsedParticleSystem.customShader) {
  48110. program = parsedParticleSystem.customShader;
  48111. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48112. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48113. }
  48114. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48115. particleSystem.customShader = program;
  48116. if (parsedParticleSystem.id) {
  48117. particleSystem.id = parsedParticleSystem.id;
  48118. }
  48119. // Auto start
  48120. if (parsedParticleSystem.preventAutoStart) {
  48121. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48122. }
  48123. // Texture
  48124. if (parsedParticleSystem.textureName) {
  48125. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48126. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48127. }
  48128. // Emitter
  48129. if (parsedParticleSystem.emitterId) {
  48130. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48131. }
  48132. else {
  48133. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48134. }
  48135. // Animations
  48136. if (parsedParticleSystem.animations) {
  48137. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48138. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48139. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48140. }
  48141. }
  48142. if (parsedParticleSystem.autoAnimate) {
  48143. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48144. }
  48145. // Particle system
  48146. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48147. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48148. particleSystem.minSize = parsedParticleSystem.minSize;
  48149. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48150. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48151. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48152. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48153. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48154. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48155. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48156. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48157. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48158. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48159. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48160. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48161. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48162. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48163. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48164. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48165. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48166. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48167. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48168. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48169. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48170. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48171. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48172. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48173. if (!particleSystem.preventAutoStart) {
  48174. particleSystem.start();
  48175. }
  48176. return particleSystem;
  48177. };
  48178. /**
  48179. * Source color is added to the destination color without alpha affecting the result.
  48180. */
  48181. ParticleSystem.BLENDMODE_ONEONE = 0;
  48182. /**
  48183. * Blend current color and particle color using particle’s alpha.
  48184. */
  48185. ParticleSystem.BLENDMODE_STANDARD = 1;
  48186. return ParticleSystem;
  48187. }());
  48188. BABYLON.ParticleSystem = ParticleSystem;
  48189. })(BABYLON || (BABYLON = {}));
  48190. //# sourceMappingURL=babylon.particleSystem.js.map
  48191. var BABYLON;
  48192. (function (BABYLON) {
  48193. /**
  48194. * Particle emitter emitting particles from the inside of a box.
  48195. * It emits the particles randomly between 2 given directions.
  48196. */
  48197. var BoxParticleEmitter = /** @class */ (function () {
  48198. // to be updated like the rest of emitters when breaking changes.
  48199. // all property should be come public variables and passed through constructor.
  48200. /**
  48201. * Creates a new instance of @see BoxParticleEmitter
  48202. * @param _particleSystem the particle system associated with the emitter
  48203. */
  48204. function BoxParticleEmitter(_particleSystem) {
  48205. this._particleSystem = _particleSystem;
  48206. }
  48207. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  48208. /**
  48209. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48210. */
  48211. get: function () {
  48212. return this._particleSystem.direction1;
  48213. },
  48214. /**
  48215. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48216. */
  48217. set: function (value) {
  48218. this._particleSystem.direction1 = value;
  48219. },
  48220. enumerable: true,
  48221. configurable: true
  48222. });
  48223. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  48224. /**
  48225. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48226. */
  48227. get: function () {
  48228. return this._particleSystem.direction2;
  48229. },
  48230. /**
  48231. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48232. */
  48233. set: function (value) {
  48234. this._particleSystem.direction2 = value;
  48235. },
  48236. enumerable: true,
  48237. configurable: true
  48238. });
  48239. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  48240. /**
  48241. * 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.
  48242. */
  48243. get: function () {
  48244. return this._particleSystem.minEmitBox;
  48245. },
  48246. /**
  48247. * 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.
  48248. */
  48249. set: function (value) {
  48250. this._particleSystem.minEmitBox = value;
  48251. },
  48252. enumerable: true,
  48253. configurable: true
  48254. });
  48255. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  48256. /**
  48257. * 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.
  48258. */
  48259. get: function () {
  48260. return this._particleSystem.maxEmitBox;
  48261. },
  48262. /**
  48263. * 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.
  48264. */
  48265. set: function (value) {
  48266. this._particleSystem.maxEmitBox = value;
  48267. },
  48268. enumerable: true,
  48269. configurable: true
  48270. });
  48271. /**
  48272. * Called by the particle System when the direction is computed for the created particle.
  48273. * @param emitPower is the power of the particle (speed)
  48274. * @param worldMatrix is the world matrix of the particle system
  48275. * @param directionToUpdate is the direction vector to update with the result
  48276. * @param particle is the particle we are computed the direction for
  48277. */
  48278. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48279. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48280. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48281. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48282. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48283. };
  48284. /**
  48285. * Called by the particle System when the position is computed for the created particle.
  48286. * @param worldMatrix is the world matrix of the particle system
  48287. * @param positionToUpdate is the position vector to update with the result
  48288. * @param particle is the particle we are computed the position for
  48289. */
  48290. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48291. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  48292. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  48293. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  48294. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48295. };
  48296. return BoxParticleEmitter;
  48297. }());
  48298. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  48299. })(BABYLON || (BABYLON = {}));
  48300. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  48301. var BABYLON;
  48302. (function (BABYLON) {
  48303. /**
  48304. * Particle emitter emitting particles from the inside of a cone.
  48305. * It emits the particles alongside the cone volume from the base to the particle.
  48306. * The emission direction might be randomized.
  48307. */
  48308. var ConeParticleEmitter = /** @class */ (function () {
  48309. /**
  48310. * Creates a new instance of @see ConeParticleEmitter
  48311. * @param radius the radius of the emission cone
  48312. * @param angles the cone base angle
  48313. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48314. */
  48315. function ConeParticleEmitter(radius,
  48316. /**
  48317. * The radius of the emission cone.
  48318. */
  48319. angle,
  48320. /**
  48321. * The cone base angle.
  48322. */
  48323. directionRandomizer) {
  48324. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48325. this.angle = angle;
  48326. this.directionRandomizer = directionRandomizer;
  48327. this.radius = radius;
  48328. }
  48329. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  48330. /**
  48331. * Gets the radius of the emission cone.
  48332. */
  48333. get: function () {
  48334. return this._radius;
  48335. },
  48336. /**
  48337. * Sets the radius of the emission cone.
  48338. */
  48339. set: function (value) {
  48340. this._radius = value;
  48341. if (this.angle !== 0) {
  48342. this._height = value / Math.tan(this.angle / 2);
  48343. }
  48344. else {
  48345. this._height = 1;
  48346. }
  48347. },
  48348. enumerable: true,
  48349. configurable: true
  48350. });
  48351. /**
  48352. * Called by the particle System when the direction is computed for the created particle.
  48353. * @param emitPower is the power of the particle (speed)
  48354. * @param worldMatrix is the world matrix of the particle system
  48355. * @param directionToUpdate is the direction vector to update with the result
  48356. * @param particle is the particle we are computed the direction for
  48357. */
  48358. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48359. if (this.angle === 0) {
  48360. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  48361. }
  48362. else {
  48363. // measure the direction Vector from the emitter to the particle.
  48364. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48365. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48366. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48367. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48368. direction.x += randX;
  48369. direction.y += randY;
  48370. direction.z += randZ;
  48371. direction.normalize();
  48372. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48373. }
  48374. };
  48375. /**
  48376. * Called by the particle System when the position is computed for the created particle.
  48377. * @param worldMatrix is the world matrix of the particle system
  48378. * @param positionToUpdate is the position vector to update with the result
  48379. * @param particle is the particle we are computed the position for
  48380. */
  48381. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48382. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  48383. var h = BABYLON.Scalar.RandomRange(0, 1);
  48384. // Better distribution in a cone at normal angles.
  48385. h = 1 - h * h;
  48386. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  48387. radius = radius * h / this._height;
  48388. var randX = radius * Math.sin(s);
  48389. var randZ = radius * Math.cos(s);
  48390. var randY = h;
  48391. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48392. };
  48393. return ConeParticleEmitter;
  48394. }());
  48395. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  48396. })(BABYLON || (BABYLON = {}));
  48397. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  48398. var BABYLON;
  48399. (function (BABYLON) {
  48400. /**
  48401. * Particle emitter emitting particles from the inside of a sphere.
  48402. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  48403. */
  48404. var SphereParticleEmitter = /** @class */ (function () {
  48405. /**
  48406. * Creates a new instance of @see SphereParticleEmitter
  48407. * @param radius the radius of the emission sphere
  48408. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48409. */
  48410. function SphereParticleEmitter(
  48411. /**
  48412. * The radius of the emission sphere.
  48413. */
  48414. radius,
  48415. /**
  48416. * How much to randomize the particle direction [0-1].
  48417. */
  48418. directionRandomizer) {
  48419. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48420. this.radius = radius;
  48421. this.directionRandomizer = directionRandomizer;
  48422. }
  48423. /**
  48424. * Called by the particle System when the direction is computed for the created particle.
  48425. * @param emitPower is the power of the particle (speed)
  48426. * @param worldMatrix is the world matrix of the particle system
  48427. * @param directionToUpdate is the direction vector to update with the result
  48428. * @param particle is the particle we are computed the direction for
  48429. */
  48430. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48431. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48432. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48433. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48434. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48435. direction.x += randX;
  48436. direction.y += randY;
  48437. direction.z += randZ;
  48438. direction.normalize();
  48439. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48440. };
  48441. /**
  48442. * Called by the particle System when the position is computed for the created particle.
  48443. * @param worldMatrix is the world matrix of the particle system
  48444. * @param positionToUpdate is the position vector to update with the result
  48445. * @param particle is the particle we are computed the position for
  48446. */
  48447. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48448. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48449. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48450. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48451. var randY = this.radius * Math.cos(theta);
  48452. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48453. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48454. };
  48455. return SphereParticleEmitter;
  48456. }());
  48457. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48458. /**
  48459. * Particle emitter emitting particles from the inside of a sphere.
  48460. * It emits the particles randomly between two vectors.
  48461. */
  48462. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48463. __extends(SphereDirectedParticleEmitter, _super);
  48464. /**
  48465. * Creates a new instance of @see SphereDirectedParticleEmitter
  48466. * @param radius the radius of the emission sphere
  48467. * @param direction1 the min limit of the emission direction
  48468. * @param direction2 the max limit of the emission direction
  48469. */
  48470. function SphereDirectedParticleEmitter(radius,
  48471. /**
  48472. * The min limit of the emission direction.
  48473. */
  48474. direction1,
  48475. /**
  48476. * The max limit of the emission direction.
  48477. */
  48478. direction2) {
  48479. var _this = _super.call(this, radius) || this;
  48480. _this.direction1 = direction1;
  48481. _this.direction2 = direction2;
  48482. return _this;
  48483. }
  48484. /**
  48485. * Called by the particle System when the direction is computed for the created particle.
  48486. * @param emitPower is the power of the particle (speed)
  48487. * @param worldMatrix is the world matrix of the particle system
  48488. * @param directionToUpdate is the direction vector to update with the result
  48489. * @param particle is the particle we are computed the direction for
  48490. */
  48491. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48492. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48493. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48494. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48495. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48496. };
  48497. return SphereDirectedParticleEmitter;
  48498. }(SphereParticleEmitter));
  48499. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48500. })(BABYLON || (BABYLON = {}));
  48501. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48502. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  48503. var BABYLON;
  48504. (function (BABYLON) {
  48505. /**
  48506. * This represents a GPU particle system in Babylon.
  48507. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  48508. */
  48509. var GPUParticleSystem = /** @class */ (function () {
  48510. /**
  48511. * Instantiates a GPU particle system.
  48512. * 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.
  48513. * @param name The name of the particle system
  48514. * @param capacity The max number of particles alive at the same time
  48515. * @param scene The scene the particle system belongs to
  48516. */
  48517. function GPUParticleSystem(name, capacity, scene) {
  48518. /**
  48519. * The emitter represents the Mesh or position we are attaching the particle system to.
  48520. */
  48521. this.emitter = null;
  48522. /**
  48523. * The rendering group used by the Particle system to chose when to render.
  48524. */
  48525. this.renderingGroupId = 0;
  48526. /**
  48527. * The layer mask we are rendering the particles through.
  48528. */
  48529. this.layerMask = 0x0FFFFFFF; // TODO
  48530. this._updateVertexBuffers = {};
  48531. this._renderVertexBuffers = {};
  48532. this._currentRenderId = -1;
  48533. this._started = true;
  48534. /**
  48535. * An event triggered when the system is disposed.
  48536. */
  48537. this.onDisposeObservable = new BABYLON.Observable();
  48538. this.id = name;
  48539. this.name = name;
  48540. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48541. this._capacity = capacity;
  48542. this._engine = this._scene.getEngine();
  48543. this._scene.particleSystems.push(this);
  48544. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  48545. var updateEffectOptions = {
  48546. attributes: ["position", "age", "life", "velocity"],
  48547. uniformsNames: [],
  48548. uniformBuffersNames: [],
  48549. samplers: [],
  48550. defines: "",
  48551. fallbacks: null,
  48552. onCompiled: null,
  48553. onError: null,
  48554. indexParameters: null,
  48555. maxSimultaneousLights: 0,
  48556. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  48557. };
  48558. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  48559. }
  48560. /**
  48561. * Gets Wether the system has been started.
  48562. * @returns True if it has been started, otherwise false.
  48563. */
  48564. GPUParticleSystem.prototype.isStarted = function () {
  48565. return this._started;
  48566. };
  48567. /**
  48568. * Starts the particle system and begins to emit.
  48569. */
  48570. GPUParticleSystem.prototype.start = function () {
  48571. this._started = true;
  48572. };
  48573. /**
  48574. * Stops the particle system.
  48575. */
  48576. GPUParticleSystem.prototype.stop = function () {
  48577. this._started = false;
  48578. };
  48579. /**
  48580. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48581. */
  48582. GPUParticleSystem.prototype.animate = function () {
  48583. // Do nothing
  48584. };
  48585. GPUParticleSystem.prototype._initialize = function () {
  48586. if (this._renderVAO) {
  48587. return;
  48588. }
  48589. var data = new Array();
  48590. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  48591. // position
  48592. data.push(0.0);
  48593. data.push(0.0);
  48594. data.push(0.0);
  48595. var life = 1 + Math.random() * 10; // TODO: var
  48596. data.push(life + 1); // create the particle as a dead one to create a new one at start
  48597. data.push(life);
  48598. // velocity
  48599. data.push(0.0);
  48600. data.push(0.0);
  48601. data.push(0.0);
  48602. }
  48603. // Update VAO
  48604. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48605. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  48606. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  48607. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  48608. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48609. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  48610. this._engine.bindArrayBuffer(null);
  48611. // Render VAO
  48612. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48613. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  48614. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  48615. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  48616. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48617. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  48618. this._engine.bindArrayBuffer(null);
  48619. // Links
  48620. this._sourceVAO = this._updateVAO;
  48621. this._targetVAO = this._renderVAO;
  48622. this._sourceBuffer = this._updateBuffer;
  48623. this._targetBuffer = this._renderBuffer;
  48624. };
  48625. /**
  48626. * Renders the particle system in its current state.
  48627. * @returns the current number of particles.
  48628. */
  48629. GPUParticleSystem.prototype.render = function () {
  48630. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  48631. return 0;
  48632. }
  48633. // Get everything ready to render
  48634. this._initialize();
  48635. if (this._currentRenderId === this._scene.getRenderId()) {
  48636. return 0;
  48637. }
  48638. this._currentRenderId = this._scene.getRenderId();
  48639. // Enable update effect
  48640. this._engine.enableEffect(this._updateEffect);
  48641. this._engine.setState(false);
  48642. // Bind source VAO
  48643. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  48644. // Update
  48645. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  48646. this._engine.setRasterizerState(false);
  48647. this._engine.beginTransformFeedback();
  48648. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48649. this._engine.endTransformFeedback();
  48650. this._engine.setRasterizerState(true);
  48651. this._engine.bindTransformFeedbackBuffer(null);
  48652. // Enable render effect
  48653. this._engine.enableEffect(this._renderEffect);
  48654. // Bind source VAO
  48655. this._engine.bindVertexArrayObject(this._targetVAO, null);
  48656. // Render
  48657. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48658. // Switch VAOs
  48659. var tmpVAO = this._sourceVAO;
  48660. this._sourceVAO = this._targetVAO;
  48661. this._targetVAO = tmpVAO;
  48662. // Switch buffers
  48663. var tmpBuffer = this._sourceBuffer;
  48664. this._sourceBuffer = this._targetBuffer;
  48665. this._targetBuffer = tmpBuffer;
  48666. return 0;
  48667. };
  48668. /**
  48669. * Rebuilds the particle system
  48670. */
  48671. GPUParticleSystem.prototype.rebuild = function () {
  48672. };
  48673. /**
  48674. * Disposes the particle system and free the associated resources.
  48675. */
  48676. GPUParticleSystem.prototype.dispose = function () {
  48677. var index = this._scene.particleSystems.indexOf(this);
  48678. if (index > -1) {
  48679. this._scene.particleSystems.splice(index, 1);
  48680. }
  48681. //TODO: this._dataBuffer.dispose();
  48682. // Callback
  48683. this.onDisposeObservable.notifyObservers(this);
  48684. this.onDisposeObservable.clear();
  48685. };
  48686. //TODO: Clone / Parse / serialize
  48687. /**
  48688. * Clones the particle system.
  48689. * @param name The name of the cloned object
  48690. * @param newEmitter The new emitter to use
  48691. * @returns the cloned particle system
  48692. */
  48693. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  48694. return null;
  48695. };
  48696. /**
  48697. * Serializes the particle system to a JSON object.
  48698. * @returns the JSON object
  48699. */
  48700. GPUParticleSystem.prototype.serialize = function () {
  48701. };
  48702. return GPUParticleSystem;
  48703. }());
  48704. BABYLON.GPUParticleSystem = GPUParticleSystem;
  48705. })(BABYLON || (BABYLON = {}));
  48706. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  48707. var BABYLON;
  48708. (function (BABYLON) {
  48709. /**
  48710. * Represents one particle of a solid particle system.
  48711. * @see SolidParticleSystem
  48712. */
  48713. var SolidParticle = /** @class */ (function () {
  48714. /**
  48715. * Creates a Solid Particle object.
  48716. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48717. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48718. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48719. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  48720. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  48721. * @param shapeId (integer) is the model shape identifier in the SPS.
  48722. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48723. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  48724. */
  48725. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48726. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  48727. /**
  48728. * particle global index
  48729. */
  48730. this.idx = 0;
  48731. /**
  48732. * The color of the particle
  48733. */
  48734. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48735. /**
  48736. * The world space position of the particle.
  48737. */
  48738. this.position = BABYLON.Vector3.Zero();
  48739. /**
  48740. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  48741. */
  48742. this.rotation = BABYLON.Vector3.Zero();
  48743. /**
  48744. * The scaling of the particle.
  48745. */
  48746. this.scaling = BABYLON.Vector3.One();
  48747. /**
  48748. * The uvs of the particle.
  48749. */
  48750. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  48751. /**
  48752. * The current speed of the particle.
  48753. */
  48754. this.velocity = BABYLON.Vector3.Zero();
  48755. /**
  48756. * The pivot point in the particle local space.
  48757. */
  48758. this.pivot = BABYLON.Vector3.Zero();
  48759. /**
  48760. * Is the particle active or not ?
  48761. */
  48762. this.alive = true;
  48763. /**
  48764. * Is the particle visible or not ?
  48765. */
  48766. this.isVisible = true;
  48767. /**
  48768. * Index of this particle in the global "positions" array (Internal use)
  48769. */
  48770. this._pos = 0;
  48771. /**
  48772. * Index of this particle in the global "indices" array (Internal use)
  48773. */
  48774. this._ind = 0;
  48775. /**
  48776. * ModelShape id of this particle
  48777. */
  48778. this.shapeId = 0;
  48779. /**
  48780. * Index of the particle in its shape id (Internal use)
  48781. */
  48782. this.idxInShape = 0;
  48783. /**
  48784. * Still set as invisible in order to skip useless computations (Internal use)
  48785. */
  48786. this._stillInvisible = false;
  48787. this.idx = particleIndex;
  48788. this._pos = positionIndex;
  48789. this._ind = indiceIndex;
  48790. this._model = model;
  48791. this.shapeId = shapeId;
  48792. this.idxInShape = idxInShape;
  48793. this._sps = sps;
  48794. if (modelBoundingInfo) {
  48795. this._modelBoundingInfo = modelBoundingInfo;
  48796. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48797. }
  48798. }
  48799. Object.defineProperty(SolidParticle.prototype, "scale", {
  48800. /**
  48801. * Legacy support, changed scale to scaling
  48802. */
  48803. get: function () {
  48804. return this.scaling;
  48805. },
  48806. /**
  48807. * Legacy support, changed scale to scaling
  48808. */
  48809. set: function (scale) {
  48810. this.scaling = scale;
  48811. },
  48812. enumerable: true,
  48813. configurable: true
  48814. });
  48815. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48816. /**
  48817. * Legacy support, changed quaternion to rotationQuaternion
  48818. */
  48819. get: function () {
  48820. return this.rotationQuaternion;
  48821. },
  48822. /**
  48823. * Legacy support, changed quaternion to rotationQuaternion
  48824. */
  48825. set: function (q) {
  48826. this.rotationQuaternion = q;
  48827. },
  48828. enumerable: true,
  48829. configurable: true
  48830. });
  48831. /**
  48832. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48833. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48834. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  48835. * @returns true if it intersects
  48836. */
  48837. SolidParticle.prototype.intersectsMesh = function (target) {
  48838. if (!this._boundingInfo || !target._boundingInfo) {
  48839. return false;
  48840. }
  48841. if (this._sps._bSphereOnly) {
  48842. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48843. }
  48844. return this._boundingInfo.intersects(target._boundingInfo, false);
  48845. };
  48846. return SolidParticle;
  48847. }());
  48848. BABYLON.SolidParticle = SolidParticle;
  48849. /**
  48850. * Represents the shape of the model used by one particle of a solid particle system.
  48851. * SPS internal tool, don't use it manually.
  48852. * @see SolidParticleSystem
  48853. */
  48854. var ModelShape = /** @class */ (function () {
  48855. /**
  48856. * 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.
  48857. * SPS internal tool, don't use it manually.
  48858. * @ignore
  48859. */
  48860. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  48861. /**
  48862. * length of the shape in the model indices array (internal use)
  48863. */
  48864. this._indicesLength = 0;
  48865. this.shapeID = id;
  48866. this._shape = shape;
  48867. this._indicesLength = indicesLength;
  48868. this._shapeUV = shapeUV;
  48869. this._positionFunction = posFunction;
  48870. this._vertexFunction = vtxFunction;
  48871. }
  48872. return ModelShape;
  48873. }());
  48874. BABYLON.ModelShape = ModelShape;
  48875. /**
  48876. * Represents a Depth Sorted Particle in the solid particle system.
  48877. * @see SolidParticleSystem
  48878. */
  48879. var DepthSortedParticle = /** @class */ (function () {
  48880. function DepthSortedParticle() {
  48881. /**
  48882. * Index of the particle in the "indices" array
  48883. */
  48884. this.ind = 0;
  48885. /**
  48886. * Length of the particle shape in the "indices" array
  48887. */
  48888. this.indicesLength = 0;
  48889. /**
  48890. * Squared distance from the particle to the camera
  48891. */
  48892. this.sqDistance = 0.0;
  48893. }
  48894. return DepthSortedParticle;
  48895. }());
  48896. BABYLON.DepthSortedParticle = DepthSortedParticle;
  48897. })(BABYLON || (BABYLON = {}));
  48898. //# sourceMappingURL=babylon.solidParticle.js.map
  48899. var BABYLON;
  48900. (function (BABYLON) {
  48901. /**
  48902. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  48903. *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.
  48904. * The SPS is also a particle system. It provides some methods to manage the particles.
  48905. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  48906. *
  48907. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  48908. */
  48909. var SolidParticleSystem = /** @class */ (function () {
  48910. /**
  48911. * Creates a SPS (Solid Particle System) object.
  48912. * @param name (String) is the SPS name, this will be the underlying mesh name.
  48913. * @param scene (Scene) is the scene in which the SPS is added.
  48914. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  48915. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  48916. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  48917. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  48918. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  48919. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  48920. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  48921. */
  48922. function SolidParticleSystem(name, scene, options) {
  48923. /**
  48924. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  48925. * Example : var p = SPS.particles[i];
  48926. */
  48927. this.particles = new Array();
  48928. /**
  48929. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  48930. */
  48931. this.nbParticles = 0;
  48932. /**
  48933. * If the particles must ever face the camera (default false). Useful for planar particles.
  48934. */
  48935. this.billboard = false;
  48936. /**
  48937. * Recompute normals when adding a shape
  48938. */
  48939. this.recomputeNormals = true;
  48940. /**
  48941. * This a counter ofr your own usage. It's not set by any SPS functions.
  48942. */
  48943. this.counter = 0;
  48944. /**
  48945. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  48946. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  48947. */
  48948. this.vars = {};
  48949. /**
  48950. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  48951. */
  48952. this._bSphereOnly = false;
  48953. /**
  48954. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  48955. */
  48956. this._bSphereRadiusFactor = 1.0;
  48957. this._positions = new Array();
  48958. this._indices = new Array();
  48959. this._normals = new Array();
  48960. this._colors = new Array();
  48961. this._uvs = new Array();
  48962. this._index = 0; // indices index
  48963. this._updatable = true;
  48964. this._pickable = false;
  48965. this._isVisibilityBoxLocked = false;
  48966. this._alwaysVisible = false;
  48967. this._depthSort = false;
  48968. this._shapeCounter = 0;
  48969. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  48970. this._color = new BABYLON.Color4(0, 0, 0, 0);
  48971. this._computeParticleColor = true;
  48972. this._computeParticleTexture = true;
  48973. this._computeParticleRotation = true;
  48974. this._computeParticleVertex = false;
  48975. this._computeBoundingBox = false;
  48976. this._depthSortParticles = true;
  48977. this._cam_axisZ = BABYLON.Vector3.Zero();
  48978. this._cam_axisY = BABYLON.Vector3.Zero();
  48979. this._cam_axisX = BABYLON.Vector3.Zero();
  48980. this._axisZ = BABYLON.Axis.Z;
  48981. this._camDir = BABYLON.Vector3.Zero();
  48982. this._camInvertedPosition = BABYLON.Vector3.Zero();
  48983. this._rotMatrix = new BABYLON.Matrix();
  48984. this._invertMatrix = new BABYLON.Matrix();
  48985. this._rotated = BABYLON.Vector3.Zero();
  48986. this._quaternion = new BABYLON.Quaternion();
  48987. this._vertex = BABYLON.Vector3.Zero();
  48988. this._normal = BABYLON.Vector3.Zero();
  48989. this._yaw = 0.0;
  48990. this._pitch = 0.0;
  48991. this._roll = 0.0;
  48992. this._halfroll = 0.0;
  48993. this._halfpitch = 0.0;
  48994. this._halfyaw = 0.0;
  48995. this._sinRoll = 0.0;
  48996. this._cosRoll = 0.0;
  48997. this._sinPitch = 0.0;
  48998. this._cosPitch = 0.0;
  48999. this._sinYaw = 0.0;
  49000. this._cosYaw = 0.0;
  49001. this._mustUnrotateFixedNormals = false;
  49002. this._minimum = BABYLON.Tmp.Vector3[0];
  49003. this._maximum = BABYLON.Tmp.Vector3[1];
  49004. this._minBbox = BABYLON.Tmp.Vector3[4];
  49005. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49006. this._particlesIntersect = false;
  49007. this._depthSortFunction = function (p1, p2) {
  49008. return (p2.sqDistance - p1.sqDistance);
  49009. };
  49010. this._needs32Bits = false;
  49011. this.name = name;
  49012. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49013. this._camera = scene.activeCamera;
  49014. this._pickable = options ? options.isPickable : false;
  49015. this._depthSort = options ? options.enableDepthSort : false;
  49016. this._particlesIntersect = options ? options.particleIntersection : false;
  49017. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49018. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49019. if (options && options.updatable) {
  49020. this._updatable = options.updatable;
  49021. }
  49022. else {
  49023. this._updatable = true;
  49024. }
  49025. if (this._pickable) {
  49026. this.pickedParticles = [];
  49027. }
  49028. if (this._depthSort) {
  49029. this.depthSortedParticles = [];
  49030. }
  49031. }
  49032. /**
  49033. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49034. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49035. * @returns the created mesh
  49036. */
  49037. SolidParticleSystem.prototype.buildMesh = function () {
  49038. if (this.nbParticles === 0) {
  49039. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49040. this.addShape(triangle, 1);
  49041. triangle.dispose();
  49042. }
  49043. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49044. this._positions32 = new Float32Array(this._positions);
  49045. this._uvs32 = new Float32Array(this._uvs);
  49046. this._colors32 = new Float32Array(this._colors);
  49047. if (this.recomputeNormals) {
  49048. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49049. }
  49050. this._normals32 = new Float32Array(this._normals);
  49051. this._fixedNormal32 = new Float32Array(this._normals);
  49052. if (this._mustUnrotateFixedNormals) {
  49053. this._unrotateFixedNormals();
  49054. }
  49055. var vertexData = new BABYLON.VertexData();
  49056. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49057. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49058. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49059. if (this._uvs32) {
  49060. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49061. ;
  49062. }
  49063. if (this._colors32) {
  49064. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49065. }
  49066. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49067. vertexData.applyToMesh(mesh, this._updatable);
  49068. this.mesh = mesh;
  49069. this.mesh.isPickable = this._pickable;
  49070. // free memory
  49071. if (!this._depthSort) {
  49072. this._indices = null;
  49073. }
  49074. this._positions = null;
  49075. this._normals = null;
  49076. this._uvs = null;
  49077. this._colors = null;
  49078. if (!this._updatable) {
  49079. this.particles.length = 0;
  49080. }
  49081. return mesh;
  49082. };
  49083. /**
  49084. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49085. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49086. * Thus the particles generated from `digest()` have their property `position` set yet.
  49087. * @param mesh ( Mesh ) is the mesh to be digested
  49088. * @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
  49089. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49090. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49091. * @returns the current SPS
  49092. */
  49093. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49094. var size = (options && options.facetNb) || 1;
  49095. var number = (options && options.number) || 0;
  49096. var delta = (options && options.delta) || 0;
  49097. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49098. var meshInd = mesh.getIndices();
  49099. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49100. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49101. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49102. var f = 0; // facet counter
  49103. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49104. // compute size from number
  49105. if (number) {
  49106. number = (number > totalFacets) ? totalFacets : number;
  49107. size = Math.round(totalFacets / number);
  49108. delta = 0;
  49109. }
  49110. else {
  49111. size = (size > totalFacets) ? totalFacets : size;
  49112. }
  49113. var facetPos = []; // submesh positions
  49114. var facetInd = []; // submesh indices
  49115. var facetUV = []; // submesh UV
  49116. var facetCol = []; // submesh colors
  49117. var barycenter = BABYLON.Tmp.Vector3[0];
  49118. var sizeO = size;
  49119. while (f < totalFacets) {
  49120. size = sizeO + Math.floor((1 + delta) * Math.random());
  49121. if (f > totalFacets - size) {
  49122. size = totalFacets - f;
  49123. }
  49124. // reset temp arrays
  49125. facetPos.length = 0;
  49126. facetInd.length = 0;
  49127. facetUV.length = 0;
  49128. facetCol.length = 0;
  49129. // iterate over "size" facets
  49130. var fi = 0;
  49131. for (var j = f * 3; j < (f + size) * 3; j++) {
  49132. facetInd.push(fi);
  49133. var i = meshInd[j];
  49134. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49135. if (meshUV) {
  49136. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49137. }
  49138. if (meshCol) {
  49139. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49140. }
  49141. fi++;
  49142. }
  49143. // create a model shape for each single particle
  49144. var idx = this.nbParticles;
  49145. var shape = this._posToShape(facetPos);
  49146. var shapeUV = this._uvsToShapeUV(facetUV);
  49147. // compute the barycenter of the shape
  49148. var v;
  49149. for (v = 0; v < shape.length; v++) {
  49150. barycenter.addInPlace(shape[v]);
  49151. }
  49152. barycenter.scaleInPlace(1 / shape.length);
  49153. // shift the shape from its barycenter to the origin
  49154. for (v = 0; v < shape.length; v++) {
  49155. shape[v].subtractInPlace(barycenter);
  49156. }
  49157. var bInfo;
  49158. if (this._particlesIntersect) {
  49159. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49160. }
  49161. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  49162. // add the particle in the SPS
  49163. var currentPos = this._positions.length;
  49164. var currentInd = this._indices.length;
  49165. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49166. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  49167. // initialize the particle position
  49168. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49169. this._index += shape.length;
  49170. idx++;
  49171. this.nbParticles++;
  49172. this._shapeCounter++;
  49173. f += size;
  49174. }
  49175. return this;
  49176. };
  49177. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  49178. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  49179. var index = 0;
  49180. var idx = 0;
  49181. for (var p = 0; p < this.particles.length; p++) {
  49182. this._particle = this.particles[p];
  49183. this._shape = this._particle._model._shape;
  49184. if (this._particle.rotationQuaternion) {
  49185. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49186. }
  49187. else {
  49188. this._yaw = this._particle.rotation.y;
  49189. this._pitch = this._particle.rotation.x;
  49190. this._roll = this._particle.rotation.z;
  49191. this._quaternionRotationYPR();
  49192. }
  49193. this._quaternionToRotationMatrix();
  49194. this._rotMatrix.invertToRef(this._invertMatrix);
  49195. for (var pt = 0; pt < this._shape.length; pt++) {
  49196. idx = index + pt * 3;
  49197. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  49198. this._fixedNormal32[idx] = this._normal.x;
  49199. this._fixedNormal32[idx + 1] = this._normal.y;
  49200. this._fixedNormal32[idx + 2] = this._normal.z;
  49201. }
  49202. index = idx + 3;
  49203. }
  49204. };
  49205. //reset copy
  49206. SolidParticleSystem.prototype._resetCopy = function () {
  49207. this._copy.position.x = 0;
  49208. this._copy.position.y = 0;
  49209. this._copy.position.z = 0;
  49210. this._copy.rotation.x = 0;
  49211. this._copy.rotation.y = 0;
  49212. this._copy.rotation.z = 0;
  49213. this._copy.rotationQuaternion = null;
  49214. this._copy.scaling.x = 1.0;
  49215. this._copy.scaling.y = 1.0;
  49216. this._copy.scaling.z = 1.0;
  49217. this._copy.uvs.x = 0;
  49218. this._copy.uvs.y = 0;
  49219. this._copy.uvs.z = 1.0;
  49220. this._copy.uvs.w = 1.0;
  49221. this._copy.color = null;
  49222. };
  49223. // _meshBuilder : inserts the shape model in the global SPS mesh
  49224. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49225. var i;
  49226. var u = 0;
  49227. var c = 0;
  49228. var n = 0;
  49229. this._resetCopy();
  49230. if (options && options.positionFunction) {
  49231. options.positionFunction(this._copy, idx, idxInShape);
  49232. this._mustUnrotateFixedNormals = true;
  49233. }
  49234. if (this._copy.rotationQuaternion) {
  49235. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49236. }
  49237. else {
  49238. this._yaw = this._copy.rotation.y;
  49239. this._pitch = this._copy.rotation.x;
  49240. this._roll = this._copy.rotation.z;
  49241. this._quaternionRotationYPR();
  49242. }
  49243. this._quaternionToRotationMatrix();
  49244. for (i = 0; i < shape.length; i++) {
  49245. this._vertex.x = shape[i].x;
  49246. this._vertex.y = shape[i].y;
  49247. this._vertex.z = shape[i].z;
  49248. if (options && options.vertexFunction) {
  49249. options.vertexFunction(this._copy, this._vertex, i);
  49250. }
  49251. this._vertex.x *= this._copy.scaling.x;
  49252. this._vertex.y *= this._copy.scaling.y;
  49253. this._vertex.z *= this._copy.scaling.z;
  49254. this._vertex.x += this._copy.pivot.x;
  49255. this._vertex.y += this._copy.pivot.y;
  49256. this._vertex.z += this._copy.pivot.z;
  49257. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49258. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49259. if (meshUV) {
  49260. 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);
  49261. u += 2;
  49262. }
  49263. if (this._copy.color) {
  49264. this._color = this._copy.color;
  49265. }
  49266. else if (meshCol && meshCol[c] !== undefined) {
  49267. this._color.r = meshCol[c];
  49268. this._color.g = meshCol[c + 1];
  49269. this._color.b = meshCol[c + 2];
  49270. this._color.a = meshCol[c + 3];
  49271. }
  49272. else {
  49273. this._color.r = 1.0;
  49274. this._color.g = 1.0;
  49275. this._color.b = 1.0;
  49276. this._color.a = 1.0;
  49277. }
  49278. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49279. c += 4;
  49280. if (!this.recomputeNormals && meshNor) {
  49281. this._normal.x = meshNor[n];
  49282. this._normal.y = meshNor[n + 1];
  49283. this._normal.z = meshNor[n + 2];
  49284. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49285. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49286. n += 3;
  49287. }
  49288. }
  49289. for (i = 0; i < meshInd.length; i++) {
  49290. var current_ind = p + meshInd[i];
  49291. indices.push(current_ind);
  49292. if (current_ind > 65535) {
  49293. this._needs32Bits = true;
  49294. }
  49295. }
  49296. if (this._pickable) {
  49297. var nbfaces = meshInd.length / 3;
  49298. for (i = 0; i < nbfaces; i++) {
  49299. this.pickedParticles.push({ idx: idx, faceId: i });
  49300. }
  49301. }
  49302. if (this._depthSort) {
  49303. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49304. }
  49305. return this._copy;
  49306. };
  49307. // returns a shape array from positions array
  49308. SolidParticleSystem.prototype._posToShape = function (positions) {
  49309. var shape = [];
  49310. for (var i = 0; i < positions.length; i += 3) {
  49311. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49312. }
  49313. return shape;
  49314. };
  49315. // returns a shapeUV array from a Vector4 uvs
  49316. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49317. var shapeUV = [];
  49318. if (uvs) {
  49319. for (var i = 0; i < uvs.length; i++)
  49320. shapeUV.push(uvs[i]);
  49321. }
  49322. return shapeUV;
  49323. };
  49324. // adds a new particle object in the particles array
  49325. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49326. if (bInfo === void 0) { bInfo = null; }
  49327. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49328. this.particles.push(sp);
  49329. return sp;
  49330. };
  49331. /**
  49332. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49333. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49334. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49335. * @param nb (positive integer) the number of particles to be created from this model
  49336. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  49337. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  49338. * @returns the number of shapes in the system
  49339. */
  49340. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49341. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49342. var meshInd = mesh.getIndices();
  49343. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49344. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49345. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49346. var bbInfo;
  49347. if (this._particlesIntersect) {
  49348. bbInfo = mesh.getBoundingInfo();
  49349. }
  49350. var shape = this._posToShape(meshPos);
  49351. var shapeUV = this._uvsToShapeUV(meshUV);
  49352. var posfunc = options ? options.positionFunction : null;
  49353. var vtxfunc = options ? options.vertexFunction : null;
  49354. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  49355. // particles
  49356. var sp;
  49357. var currentCopy;
  49358. var idx = this.nbParticles;
  49359. for (var i = 0; i < nb; i++) {
  49360. var currentPos = this._positions.length;
  49361. var currentInd = this._indices.length;
  49362. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49363. if (this._updatable) {
  49364. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  49365. sp.position.copyFrom(currentCopy.position);
  49366. sp.rotation.copyFrom(currentCopy.rotation);
  49367. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  49368. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  49369. }
  49370. if (currentCopy.color && sp.color) {
  49371. sp.color.copyFrom(currentCopy.color);
  49372. }
  49373. sp.scaling.copyFrom(currentCopy.scaling);
  49374. sp.uvs.copyFrom(currentCopy.uvs);
  49375. }
  49376. this._index += shape.length;
  49377. idx++;
  49378. }
  49379. this.nbParticles += nb;
  49380. this._shapeCounter++;
  49381. return this._shapeCounter - 1;
  49382. };
  49383. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49384. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49385. this._resetCopy();
  49386. if (particle._model._positionFunction) {
  49387. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49388. }
  49389. if (this._copy.rotationQuaternion) {
  49390. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49391. }
  49392. else {
  49393. this._yaw = this._copy.rotation.y;
  49394. this._pitch = this._copy.rotation.x;
  49395. this._roll = this._copy.rotation.z;
  49396. this._quaternionRotationYPR();
  49397. }
  49398. this._quaternionToRotationMatrix();
  49399. this._shape = particle._model._shape;
  49400. for (var pt = 0; pt < this._shape.length; pt++) {
  49401. this._vertex.x = this._shape[pt].x;
  49402. this._vertex.y = this._shape[pt].y;
  49403. this._vertex.z = this._shape[pt].z;
  49404. if (particle._model._vertexFunction) {
  49405. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49406. }
  49407. this._vertex.x *= this._copy.scaling.x;
  49408. this._vertex.y *= this._copy.scaling.y;
  49409. this._vertex.z *= this._copy.scaling.z;
  49410. this._vertex.x += this._copy.pivot.x;
  49411. this._vertex.y += this._copy.pivot.y;
  49412. this._vertex.z += this._copy.pivot.z;
  49413. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49414. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49415. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49416. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49417. }
  49418. particle.position.x = 0.0;
  49419. particle.position.y = 0.0;
  49420. particle.position.z = 0.0;
  49421. particle.rotation.x = 0.0;
  49422. particle.rotation.y = 0.0;
  49423. particle.rotation.z = 0.0;
  49424. particle.rotationQuaternion = null;
  49425. particle.scaling.x = 1.0;
  49426. particle.scaling.y = 1.0;
  49427. particle.scaling.z = 1.0;
  49428. };
  49429. /**
  49430. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49431. * @returns the SPS.
  49432. */
  49433. SolidParticleSystem.prototype.rebuildMesh = function () {
  49434. for (var p = 0; p < this.particles.length; p++) {
  49435. this._rebuildParticle(this.particles[p]);
  49436. }
  49437. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49438. return this;
  49439. };
  49440. /**
  49441. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49442. * This method calls `updateParticle()` for each particle of the SPS.
  49443. * For an animated SPS, it is usually called within the render loop.
  49444. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49445. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49446. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49447. * @returns the SPS.
  49448. */
  49449. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49450. if (start === void 0) { start = 0; }
  49451. if (end === void 0) { end = this.nbParticles - 1; }
  49452. if (update === void 0) { update = true; }
  49453. if (!this._updatable) {
  49454. return this;
  49455. }
  49456. // custom beforeUpdate
  49457. this.beforeUpdateParticles(start, end, update);
  49458. this._cam_axisX.x = 1.0;
  49459. this._cam_axisX.y = 0.0;
  49460. this._cam_axisX.z = 0.0;
  49461. this._cam_axisY.x = 0.0;
  49462. this._cam_axisY.y = 1.0;
  49463. this._cam_axisY.z = 0.0;
  49464. this._cam_axisZ.x = 0.0;
  49465. this._cam_axisZ.y = 0.0;
  49466. this._cam_axisZ.z = 1.0;
  49467. // cases when the World Matrix is to be computed first
  49468. if (this.billboard || this._depthSort) {
  49469. this.mesh.computeWorldMatrix(true);
  49470. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49471. }
  49472. // if the particles will always face the camera
  49473. if (this.billboard) {
  49474. // compute the camera position and un-rotate it by the current mesh rotation
  49475. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49476. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49477. this._cam_axisZ.normalize();
  49478. // same for camera up vector extracted from the cam view matrix
  49479. var view = this._camera.getViewMatrix(true);
  49480. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49481. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49482. this._cam_axisY.normalize();
  49483. this._cam_axisX.normalize();
  49484. }
  49485. // if depthSort, compute the camera global position in the mesh local system
  49486. if (this._depthSort) {
  49487. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49488. }
  49489. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49490. var idx = 0; // current position index in the global array positions32
  49491. var index = 0; // position start index in the global array positions32 of the current particle
  49492. var colidx = 0; // current color index in the global array colors32
  49493. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49494. var uvidx = 0; // current uv index in the global array uvs32
  49495. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49496. var pt = 0; // current index in the particle model shape
  49497. if (this.mesh.isFacetDataEnabled) {
  49498. this._computeBoundingBox = true;
  49499. }
  49500. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49501. if (this._computeBoundingBox) {
  49502. if (start == 0 && end == this.nbParticles - 1) {
  49503. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49504. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49505. }
  49506. else {
  49507. if (this.mesh._boundingInfo) {
  49508. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49509. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49510. }
  49511. }
  49512. }
  49513. // particle loop
  49514. index = this.particles[start]._pos;
  49515. var vpos = (index / 3) | 0;
  49516. colorIndex = vpos * 4;
  49517. uvIndex = vpos * 2;
  49518. for (var p = start; p <= end; p++) {
  49519. this._particle = this.particles[p];
  49520. this._shape = this._particle._model._shape;
  49521. this._shapeUV = this._particle._model._shapeUV;
  49522. // call to custom user function to update the particle properties
  49523. this.updateParticle(this._particle);
  49524. // camera-particle distance for depth sorting
  49525. if (this._depthSort && this._depthSortParticles) {
  49526. var dsp = this.depthSortedParticles[p];
  49527. dsp.ind = this._particle._ind;
  49528. dsp.indicesLength = this._particle._model._indicesLength;
  49529. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49530. }
  49531. // skip the computations for inactive or already invisible particles
  49532. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49533. // increment indexes for the next particle
  49534. pt = this._shape.length;
  49535. index += pt * 3;
  49536. colorIndex += pt * 4;
  49537. uvIndex += pt * 2;
  49538. continue;
  49539. }
  49540. if (this._particle.isVisible) {
  49541. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49542. // particle rotation matrix
  49543. if (this.billboard) {
  49544. this._particle.rotation.x = 0.0;
  49545. this._particle.rotation.y = 0.0;
  49546. }
  49547. if (this._computeParticleRotation || this.billboard) {
  49548. if (this._particle.rotationQuaternion) {
  49549. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49550. }
  49551. else {
  49552. this._yaw = this._particle.rotation.y;
  49553. this._pitch = this._particle.rotation.x;
  49554. this._roll = this._particle.rotation.z;
  49555. this._quaternionRotationYPR();
  49556. }
  49557. this._quaternionToRotationMatrix();
  49558. }
  49559. // particle vertex loop
  49560. for (pt = 0; pt < this._shape.length; pt++) {
  49561. idx = index + pt * 3;
  49562. colidx = colorIndex + pt * 4;
  49563. uvidx = uvIndex + pt * 2;
  49564. this._vertex.x = this._shape[pt].x;
  49565. this._vertex.y = this._shape[pt].y;
  49566. this._vertex.z = this._shape[pt].z;
  49567. if (this._computeParticleVertex) {
  49568. this.updateParticleVertex(this._particle, this._vertex, pt);
  49569. }
  49570. // positions
  49571. this._vertex.x *= this._particle.scaling.x;
  49572. this._vertex.y *= this._particle.scaling.y;
  49573. this._vertex.z *= this._particle.scaling.z;
  49574. this._vertex.x += this._particle.pivot.x;
  49575. this._vertex.y += this._particle.pivot.y;
  49576. this._vertex.z += this._particle.pivot.z;
  49577. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49578. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49579. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49580. this._positions32[idx] = 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;
  49581. this._positions32[idx + 1] = 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;
  49582. this._positions32[idx + 2] = 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;
  49583. if (this._computeBoundingBox) {
  49584. if (this._positions32[idx] < this._minimum.x) {
  49585. this._minimum.x = this._positions32[idx];
  49586. }
  49587. if (this._positions32[idx] > this._maximum.x) {
  49588. this._maximum.x = this._positions32[idx];
  49589. }
  49590. if (this._positions32[idx + 1] < this._minimum.y) {
  49591. this._minimum.y = this._positions32[idx + 1];
  49592. }
  49593. if (this._positions32[idx + 1] > this._maximum.y) {
  49594. this._maximum.y = this._positions32[idx + 1];
  49595. }
  49596. if (this._positions32[idx + 2] < this._minimum.z) {
  49597. this._minimum.z = this._positions32[idx + 2];
  49598. }
  49599. if (this._positions32[idx + 2] > this._maximum.z) {
  49600. this._maximum.z = this._positions32[idx + 2];
  49601. }
  49602. }
  49603. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49604. if (!this._computeParticleVertex) {
  49605. this._normal.x = this._fixedNormal32[idx];
  49606. this._normal.y = this._fixedNormal32[idx + 1];
  49607. this._normal.z = this._fixedNormal32[idx + 2];
  49608. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49609. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49610. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49611. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49612. 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;
  49613. 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;
  49614. }
  49615. if (this._computeParticleColor && this._particle.color) {
  49616. this._colors32[colidx] = this._particle.color.r;
  49617. this._colors32[colidx + 1] = this._particle.color.g;
  49618. this._colors32[colidx + 2] = this._particle.color.b;
  49619. this._colors32[colidx + 3] = this._particle.color.a;
  49620. }
  49621. if (this._computeParticleTexture) {
  49622. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49623. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49624. }
  49625. }
  49626. }
  49627. else {
  49628. this._particle._stillInvisible = true; // mark the particle as invisible
  49629. for (pt = 0; pt < this._shape.length; pt++) {
  49630. idx = index + pt * 3;
  49631. colidx = colorIndex + pt * 4;
  49632. uvidx = uvIndex + pt * 2;
  49633. this._positions32[idx] = 0.0;
  49634. this._positions32[idx + 1] = 0.0;
  49635. this._positions32[idx + 2] = 0.0;
  49636. this._normals32[idx] = 0.0;
  49637. this._normals32[idx + 1] = 0.0;
  49638. this._normals32[idx + 2] = 0.0;
  49639. if (this._computeParticleColor && this._particle.color) {
  49640. this._colors32[colidx] = this._particle.color.r;
  49641. this._colors32[colidx + 1] = this._particle.color.g;
  49642. this._colors32[colidx + 2] = this._particle.color.b;
  49643. this._colors32[colidx + 3] = this._particle.color.a;
  49644. }
  49645. if (this._computeParticleTexture) {
  49646. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49647. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49648. }
  49649. }
  49650. }
  49651. // if the particle intersections must be computed : update the bbInfo
  49652. if (this._particlesIntersect) {
  49653. var bInfo = this._particle._boundingInfo;
  49654. var bBox = bInfo.boundingBox;
  49655. var bSphere = bInfo.boundingSphere;
  49656. if (!this._bSphereOnly) {
  49657. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49658. for (var b = 0; b < bBox.vectors.length; b++) {
  49659. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49660. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49661. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49662. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49663. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49664. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49665. 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;
  49666. 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;
  49667. 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;
  49668. }
  49669. bBox._update(this.mesh._worldMatrix);
  49670. }
  49671. // place and scale the particle bouding sphere in the SPS local system, then update it
  49672. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49673. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49674. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49675. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49676. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49677. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49678. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49679. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49680. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49681. 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));
  49682. bSphere._update(this.mesh._worldMatrix);
  49683. }
  49684. // increment indexes for the next particle
  49685. index = idx + 3;
  49686. colorIndex = colidx + 4;
  49687. uvIndex = uvidx + 2;
  49688. }
  49689. // if the VBO must be updated
  49690. if (update) {
  49691. if (this._computeParticleColor) {
  49692. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49693. }
  49694. if (this._computeParticleTexture) {
  49695. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49696. }
  49697. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49698. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  49699. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  49700. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49701. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  49702. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  49703. for (var i = 0; i < this._normals32.length; i++) {
  49704. this._fixedNormal32[i] = this._normals32[i];
  49705. }
  49706. }
  49707. if (!this.mesh.areNormalsFrozen) {
  49708. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49709. }
  49710. }
  49711. if (this._depthSort && this._depthSortParticles) {
  49712. this.depthSortedParticles.sort(this._depthSortFunction);
  49713. var dspl = this.depthSortedParticles.length;
  49714. var sorted = 0;
  49715. var lind = 0;
  49716. var sind = 0;
  49717. var sid = 0;
  49718. for (sorted = 0; sorted < dspl; sorted++) {
  49719. lind = this.depthSortedParticles[sorted].indicesLength;
  49720. sind = this.depthSortedParticles[sorted].ind;
  49721. for (var i = 0; i < lind; i++) {
  49722. this._indices32[sid] = this._indices[sind + i];
  49723. sid++;
  49724. }
  49725. }
  49726. this.mesh.updateIndices(this._indices32);
  49727. }
  49728. }
  49729. if (this._computeBoundingBox) {
  49730. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49731. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49732. }
  49733. this.afterUpdateParticles(start, end, update);
  49734. return this;
  49735. };
  49736. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49737. this._halfroll = this._roll * 0.5;
  49738. this._halfpitch = this._pitch * 0.5;
  49739. this._halfyaw = this._yaw * 0.5;
  49740. this._sinRoll = Math.sin(this._halfroll);
  49741. this._cosRoll = Math.cos(this._halfroll);
  49742. this._sinPitch = Math.sin(this._halfpitch);
  49743. this._cosPitch = Math.cos(this._halfpitch);
  49744. this._sinYaw = Math.sin(this._halfyaw);
  49745. this._cosYaw = Math.cos(this._halfyaw);
  49746. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  49747. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  49748. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  49749. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  49750. };
  49751. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49752. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49753. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49754. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49755. this._rotMatrix.m[3] = 0;
  49756. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49757. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49758. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49759. this._rotMatrix.m[7] = 0;
  49760. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49761. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49762. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49763. this._rotMatrix.m[11] = 0;
  49764. this._rotMatrix.m[12] = 0;
  49765. this._rotMatrix.m[13] = 0;
  49766. this._rotMatrix.m[14] = 0;
  49767. this._rotMatrix.m[15] = 1.0;
  49768. };
  49769. /**
  49770. * Disposes the SPS.
  49771. */
  49772. SolidParticleSystem.prototype.dispose = function () {
  49773. this.mesh.dispose();
  49774. this.vars = null;
  49775. // drop references to internal big arrays for the GC
  49776. this._positions = null;
  49777. this._indices = null;
  49778. this._normals = null;
  49779. this._uvs = null;
  49780. this._colors = null;
  49781. this._indices32 = null;
  49782. this._positions32 = null;
  49783. this._normals32 = null;
  49784. this._fixedNormal32 = null;
  49785. this._uvs32 = null;
  49786. this._colors32 = null;
  49787. this.pickedParticles = null;
  49788. };
  49789. /**
  49790. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49791. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49792. * @returns the SPS.
  49793. */
  49794. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49795. if (!this._isVisibilityBoxLocked) {
  49796. this.mesh.refreshBoundingInfo();
  49797. }
  49798. return this;
  49799. };
  49800. /**
  49801. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49802. * @param size the size (float) of the visibility box
  49803. * note : this doesn't lock the SPS mesh bounding box.
  49804. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49805. */
  49806. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49807. var vis = size / 2;
  49808. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49809. };
  49810. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49811. /**
  49812. * Gets whether the SPS as always visible or not
  49813. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49814. */
  49815. get: function () {
  49816. return this._alwaysVisible;
  49817. },
  49818. /**
  49819. * Sets the SPS as always visible or not
  49820. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49821. */
  49822. set: function (val) {
  49823. this._alwaysVisible = val;
  49824. this.mesh.alwaysSelectAsActiveMesh = val;
  49825. },
  49826. enumerable: true,
  49827. configurable: true
  49828. });
  49829. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49830. /**
  49831. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49832. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49833. */
  49834. get: function () {
  49835. return this._isVisibilityBoxLocked;
  49836. },
  49837. /**
  49838. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49839. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49840. */
  49841. set: function (val) {
  49842. this._isVisibilityBoxLocked = val;
  49843. var boundingInfo = this.mesh.getBoundingInfo();
  49844. boundingInfo.isLocked = val;
  49845. },
  49846. enumerable: true,
  49847. configurable: true
  49848. });
  49849. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49850. /**
  49851. * Gets if `setParticles()` computes the particle rotations or not.
  49852. * Default value : true. The SPS is faster when it's set to false.
  49853. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49854. */
  49855. get: function () {
  49856. return this._computeParticleRotation;
  49857. },
  49858. /**
  49859. * Tells to `setParticles()` to compute the particle rotations or not.
  49860. * Default value : true. The SPS is faster when it's set to false.
  49861. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49862. */
  49863. set: function (val) {
  49864. this._computeParticleRotation = val;
  49865. },
  49866. enumerable: true,
  49867. configurable: true
  49868. });
  49869. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49870. /**
  49871. * Gets if `setParticles()` computes the particle colors or not.
  49872. * Default value : true. The SPS is faster when it's set to false.
  49873. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49874. */
  49875. get: function () {
  49876. return this._computeParticleColor;
  49877. },
  49878. /**
  49879. * Tells to `setParticles()` to compute the particle colors or not.
  49880. * Default value : true. The SPS is faster when it's set to false.
  49881. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49882. */
  49883. set: function (val) {
  49884. this._computeParticleColor = val;
  49885. },
  49886. enumerable: true,
  49887. configurable: true
  49888. });
  49889. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49890. /**
  49891. * Gets if `setParticles()` computes the particle textures or not.
  49892. * Default value : true. The SPS is faster when it's set to false.
  49893. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49894. */
  49895. get: function () {
  49896. return this._computeParticleTexture;
  49897. },
  49898. set: function (val) {
  49899. this._computeParticleTexture = val;
  49900. },
  49901. enumerable: true,
  49902. configurable: true
  49903. });
  49904. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  49905. /**
  49906. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  49907. * Default value : false. The SPS is faster when it's set to false.
  49908. * Note : the particle custom vertex positions aren't stored values.
  49909. */
  49910. get: function () {
  49911. return this._computeParticleVertex;
  49912. },
  49913. /**
  49914. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  49915. * Default value : false. The SPS is faster when it's set to false.
  49916. * Note : the particle custom vertex positions aren't stored values.
  49917. */
  49918. set: function (val) {
  49919. this._computeParticleVertex = val;
  49920. },
  49921. enumerable: true,
  49922. configurable: true
  49923. });
  49924. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  49925. /**
  49926. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  49927. */
  49928. get: function () {
  49929. return this._computeBoundingBox;
  49930. },
  49931. /**
  49932. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  49933. */
  49934. set: function (val) {
  49935. this._computeBoundingBox = val;
  49936. },
  49937. enumerable: true,
  49938. configurable: true
  49939. });
  49940. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  49941. /**
  49942. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  49943. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49944. * Default : `true`
  49945. */
  49946. get: function () {
  49947. return this._depthSortParticles;
  49948. },
  49949. /**
  49950. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  49951. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  49952. * Default : `true`
  49953. */
  49954. set: function (val) {
  49955. this._depthSortParticles = val;
  49956. },
  49957. enumerable: true,
  49958. configurable: true
  49959. });
  49960. // =======================================================================
  49961. // Particle behavior logic
  49962. // these following methods may be overwritten by the user to fit his needs
  49963. /**
  49964. * This function does nothing. It may be overwritten to set all the particle first values.
  49965. * The SPS doesn't call this function, you may have to call it by your own.
  49966. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49967. */
  49968. SolidParticleSystem.prototype.initParticles = function () {
  49969. };
  49970. /**
  49971. * This function does nothing. It may be overwritten to recycle a particle.
  49972. * The SPS doesn't call this function, you may have to call it by your own.
  49973. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49974. * @param particle The particle to recycle
  49975. * @returns the recycled particle
  49976. */
  49977. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  49978. return particle;
  49979. };
  49980. /**
  49981. * Updates a particle : this function should be overwritten by the user.
  49982. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  49983. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  49984. * @example : just set a particle position or velocity and recycle conditions
  49985. * @param particle The particle to update
  49986. * @returns the updated particle
  49987. */
  49988. SolidParticleSystem.prototype.updateParticle = function (particle) {
  49989. return particle;
  49990. };
  49991. /**
  49992. * Updates a vertex of a particle : it can be overwritten by the user.
  49993. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  49994. * @param particle the current particle
  49995. * @param vertex the current index of the current particle
  49996. * @param pt the index of the current vertex in the particle shape
  49997. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  49998. * @example : just set a vertex particle position
  49999. * @returns the updated vertex
  50000. */
  50001. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50002. return vertex;
  50003. };
  50004. /**
  50005. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50006. * This does nothing and may be overwritten by the user.
  50007. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50008. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50009. * @param update the boolean update value actually passed to setParticles()
  50010. */
  50011. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50012. };
  50013. /**
  50014. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50015. * This will be passed three parameters.
  50016. * This does nothing and may be overwritten by the user.
  50017. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50018. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50019. * @param update the boolean update value actually passed to setParticles()
  50020. */
  50021. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50022. };
  50023. return SolidParticleSystem;
  50024. }());
  50025. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50026. })(BABYLON || (BABYLON = {}));
  50027. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50028. var BABYLON;
  50029. (function (BABYLON) {
  50030. var ShaderMaterial = /** @class */ (function (_super) {
  50031. __extends(ShaderMaterial, _super);
  50032. function ShaderMaterial(name, scene, shaderPath, options) {
  50033. var _this = _super.call(this, name, scene) || this;
  50034. _this._textures = {};
  50035. _this._textureArrays = {};
  50036. _this._floats = {};
  50037. _this._ints = {};
  50038. _this._floatsArrays = {};
  50039. _this._colors3 = {};
  50040. _this._colors3Arrays = {};
  50041. _this._colors4 = {};
  50042. _this._vectors2 = {};
  50043. _this._vectors3 = {};
  50044. _this._vectors4 = {};
  50045. _this._matrices = {};
  50046. _this._matrices3x3 = {};
  50047. _this._matrices2x2 = {};
  50048. _this._vectors2Arrays = {};
  50049. _this._vectors3Arrays = {};
  50050. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50051. _this._shaderPath = shaderPath;
  50052. options.needAlphaBlending = options.needAlphaBlending || false;
  50053. options.needAlphaTesting = options.needAlphaTesting || false;
  50054. options.attributes = options.attributes || ["position", "normal", "uv"];
  50055. options.uniforms = options.uniforms || ["worldViewProjection"];
  50056. options.uniformBuffers = options.uniformBuffers || [];
  50057. options.samplers = options.samplers || [];
  50058. options.defines = options.defines || [];
  50059. _this._options = options;
  50060. return _this;
  50061. }
  50062. ShaderMaterial.prototype.getClassName = function () {
  50063. return "ShaderMaterial";
  50064. };
  50065. ShaderMaterial.prototype.needAlphaBlending = function () {
  50066. return this._options.needAlphaBlending;
  50067. };
  50068. ShaderMaterial.prototype.needAlphaTesting = function () {
  50069. return this._options.needAlphaTesting;
  50070. };
  50071. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50072. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50073. this._options.uniforms.push(uniformName);
  50074. }
  50075. };
  50076. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50077. if (this._options.samplers.indexOf(name) === -1) {
  50078. this._options.samplers.push(name);
  50079. }
  50080. this._textures[name] = texture;
  50081. return this;
  50082. };
  50083. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50084. if (this._options.samplers.indexOf(name) === -1) {
  50085. this._options.samplers.push(name);
  50086. }
  50087. this._checkUniform(name);
  50088. this._textureArrays[name] = textures;
  50089. return this;
  50090. };
  50091. ShaderMaterial.prototype.setFloat = function (name, value) {
  50092. this._checkUniform(name);
  50093. this._floats[name] = value;
  50094. return this;
  50095. };
  50096. ShaderMaterial.prototype.setInt = function (name, value) {
  50097. this._checkUniform(name);
  50098. this._ints[name] = value;
  50099. return this;
  50100. };
  50101. ShaderMaterial.prototype.setFloats = function (name, value) {
  50102. this._checkUniform(name);
  50103. this._floatsArrays[name] = value;
  50104. return this;
  50105. };
  50106. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50107. this._checkUniform(name);
  50108. this._colors3[name] = value;
  50109. return this;
  50110. };
  50111. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50112. this._checkUniform(name);
  50113. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50114. color.toArray(arr, arr.length);
  50115. return arr;
  50116. }, []);
  50117. return this;
  50118. };
  50119. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50120. this._checkUniform(name);
  50121. this._colors4[name] = value;
  50122. return this;
  50123. };
  50124. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50125. this._checkUniform(name);
  50126. this._vectors2[name] = value;
  50127. return this;
  50128. };
  50129. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50130. this._checkUniform(name);
  50131. this._vectors3[name] = value;
  50132. return this;
  50133. };
  50134. ShaderMaterial.prototype.setVector4 = function (name, value) {
  50135. this._checkUniform(name);
  50136. this._vectors4[name] = value;
  50137. return this;
  50138. };
  50139. ShaderMaterial.prototype.setMatrix = function (name, value) {
  50140. this._checkUniform(name);
  50141. this._matrices[name] = value;
  50142. return this;
  50143. };
  50144. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  50145. this._checkUniform(name);
  50146. this._matrices3x3[name] = value;
  50147. return this;
  50148. };
  50149. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  50150. this._checkUniform(name);
  50151. this._matrices2x2[name] = value;
  50152. return this;
  50153. };
  50154. ShaderMaterial.prototype.setArray2 = function (name, value) {
  50155. this._checkUniform(name);
  50156. this._vectors2Arrays[name] = value;
  50157. return this;
  50158. };
  50159. ShaderMaterial.prototype.setArray3 = function (name, value) {
  50160. this._checkUniform(name);
  50161. this._vectors3Arrays[name] = value;
  50162. return this;
  50163. };
  50164. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50165. if (!mesh) {
  50166. return true;
  50167. }
  50168. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  50169. return false;
  50170. }
  50171. return false;
  50172. };
  50173. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  50174. var scene = this.getScene();
  50175. var engine = scene.getEngine();
  50176. if (!this.checkReadyOnEveryCall) {
  50177. if (this._renderId === scene.getRenderId()) {
  50178. if (this._checkCache(scene, mesh, useInstances)) {
  50179. return true;
  50180. }
  50181. }
  50182. }
  50183. // Instances
  50184. var defines = [];
  50185. var attribs = [];
  50186. var fallbacks = new BABYLON.EffectFallbacks();
  50187. if (useInstances) {
  50188. defines.push("#define INSTANCES");
  50189. }
  50190. for (var index = 0; index < this._options.defines.length; index++) {
  50191. defines.push(this._options.defines[index]);
  50192. }
  50193. for (var index = 0; index < this._options.attributes.length; index++) {
  50194. attribs.push(this._options.attributes[index]);
  50195. }
  50196. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50197. attribs.push(BABYLON.VertexBuffer.ColorKind);
  50198. defines.push("#define VERTEXCOLOR");
  50199. }
  50200. // Bones
  50201. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  50202. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50203. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50204. if (mesh.numBoneInfluencers > 4) {
  50205. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50206. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50207. }
  50208. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50209. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50210. fallbacks.addCPUSkinningFallback(0, mesh);
  50211. if (this._options.uniforms.indexOf("mBones") === -1) {
  50212. this._options.uniforms.push("mBones");
  50213. }
  50214. }
  50215. else {
  50216. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50217. }
  50218. // Textures
  50219. for (var name in this._textures) {
  50220. if (!this._textures[name].isReady()) {
  50221. return false;
  50222. }
  50223. }
  50224. // Alpha test
  50225. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  50226. defines.push("#define ALPHATEST");
  50227. }
  50228. var previousEffect = this._effect;
  50229. var join = defines.join("\n");
  50230. this._effect = engine.createEffect(this._shaderPath, {
  50231. attributes: attribs,
  50232. uniformsNames: this._options.uniforms,
  50233. uniformBuffersNames: this._options.uniformBuffers,
  50234. samplers: this._options.samplers,
  50235. defines: join,
  50236. fallbacks: fallbacks,
  50237. onCompiled: this.onCompiled,
  50238. onError: this.onError
  50239. }, engine);
  50240. if (!this._effect.isReady()) {
  50241. return false;
  50242. }
  50243. if (previousEffect !== this._effect) {
  50244. scene.resetCachedMaterial();
  50245. }
  50246. this._renderId = scene.getRenderId();
  50247. return true;
  50248. };
  50249. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  50250. var scene = this.getScene();
  50251. if (!this._effect) {
  50252. return;
  50253. }
  50254. if (this._options.uniforms.indexOf("world") !== -1) {
  50255. this._effect.setMatrix("world", world);
  50256. }
  50257. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50258. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50259. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50260. }
  50261. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50262. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50263. }
  50264. };
  50265. ShaderMaterial.prototype.bind = function (world, mesh) {
  50266. // Std values
  50267. this.bindOnlyWorldMatrix(world);
  50268. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50269. if (this._options.uniforms.indexOf("view") !== -1) {
  50270. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50271. }
  50272. if (this._options.uniforms.indexOf("projection") !== -1) {
  50273. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50274. }
  50275. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50276. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50277. }
  50278. // Bones
  50279. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50280. var name;
  50281. // Texture
  50282. for (name in this._textures) {
  50283. this._effect.setTexture(name, this._textures[name]);
  50284. }
  50285. // Texture arrays
  50286. for (name in this._textureArrays) {
  50287. this._effect.setTextureArray(name, this._textureArrays[name]);
  50288. }
  50289. // Int
  50290. for (name in this._ints) {
  50291. this._effect.setInt(name, this._ints[name]);
  50292. }
  50293. // Float
  50294. for (name in this._floats) {
  50295. this._effect.setFloat(name, this._floats[name]);
  50296. }
  50297. // Floats
  50298. for (name in this._floatsArrays) {
  50299. this._effect.setArray(name, this._floatsArrays[name]);
  50300. }
  50301. // Color3
  50302. for (name in this._colors3) {
  50303. this._effect.setColor3(name, this._colors3[name]);
  50304. }
  50305. for (name in this._colors3Arrays) {
  50306. this._effect.setArray3(name, this._colors3Arrays[name]);
  50307. }
  50308. // Color4
  50309. for (name in this._colors4) {
  50310. var color = this._colors4[name];
  50311. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50312. }
  50313. // Vector2
  50314. for (name in this._vectors2) {
  50315. this._effect.setVector2(name, this._vectors2[name]);
  50316. }
  50317. // Vector3
  50318. for (name in this._vectors3) {
  50319. this._effect.setVector3(name, this._vectors3[name]);
  50320. }
  50321. // Vector4
  50322. for (name in this._vectors4) {
  50323. this._effect.setVector4(name, this._vectors4[name]);
  50324. }
  50325. // Matrix
  50326. for (name in this._matrices) {
  50327. this._effect.setMatrix(name, this._matrices[name]);
  50328. }
  50329. // Matrix 3x3
  50330. for (name in this._matrices3x3) {
  50331. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  50332. }
  50333. // Matrix 2x2
  50334. for (name in this._matrices2x2) {
  50335. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  50336. }
  50337. // Vector2Array
  50338. for (name in this._vectors2Arrays) {
  50339. this._effect.setArray2(name, this._vectors2Arrays[name]);
  50340. }
  50341. // Vector3Array
  50342. for (name in this._vectors3Arrays) {
  50343. this._effect.setArray3(name, this._vectors3Arrays[name]);
  50344. }
  50345. }
  50346. this._afterBind(mesh);
  50347. };
  50348. ShaderMaterial.prototype.getActiveTextures = function () {
  50349. var activeTextures = _super.prototype.getActiveTextures.call(this);
  50350. for (var name in this._textures) {
  50351. activeTextures.push(this._textures[name]);
  50352. }
  50353. for (var name in this._textureArrays) {
  50354. var array = this._textureArrays[name];
  50355. for (var index = 0; index < array.length; index++) {
  50356. activeTextures.push(array[index]);
  50357. }
  50358. }
  50359. return activeTextures;
  50360. };
  50361. ShaderMaterial.prototype.hasTexture = function (texture) {
  50362. if (_super.prototype.hasTexture.call(this, texture)) {
  50363. return true;
  50364. }
  50365. for (var name in this._textures) {
  50366. if (this._textures[name] === texture) {
  50367. return true;
  50368. }
  50369. }
  50370. for (var name in this._textureArrays) {
  50371. var array = this._textureArrays[name];
  50372. for (var index = 0; index < array.length; index++) {
  50373. if (array[index] === texture) {
  50374. return true;
  50375. }
  50376. }
  50377. }
  50378. return false;
  50379. };
  50380. ShaderMaterial.prototype.clone = function (name) {
  50381. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  50382. return newShaderMaterial;
  50383. };
  50384. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50385. if (forceDisposeTextures) {
  50386. var name;
  50387. for (name in this._textures) {
  50388. this._textures[name].dispose();
  50389. }
  50390. for (name in this._textureArrays) {
  50391. var array = this._textureArrays[name];
  50392. for (var index = 0; index < array.length; index++) {
  50393. array[index].dispose();
  50394. }
  50395. }
  50396. }
  50397. this._textures = {};
  50398. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50399. };
  50400. ShaderMaterial.prototype.serialize = function () {
  50401. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50402. serializationObject.customType = "BABYLON.ShaderMaterial";
  50403. serializationObject.options = this._options;
  50404. serializationObject.shaderPath = this._shaderPath;
  50405. var name;
  50406. // Texture
  50407. serializationObject.textures = {};
  50408. for (name in this._textures) {
  50409. serializationObject.textures[name] = this._textures[name].serialize();
  50410. }
  50411. // Texture arrays
  50412. serializationObject.textureArrays = {};
  50413. for (name in this._textureArrays) {
  50414. serializationObject.textureArrays[name] = [];
  50415. var array = this._textureArrays[name];
  50416. for (var index = 0; index < array.length; index++) {
  50417. serializationObject.textureArrays[name].push(array[index].serialize());
  50418. }
  50419. }
  50420. // Float
  50421. serializationObject.floats = {};
  50422. for (name in this._floats) {
  50423. serializationObject.floats[name] = this._floats[name];
  50424. }
  50425. // Float s
  50426. serializationObject.FloatArrays = {};
  50427. for (name in this._floatsArrays) {
  50428. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  50429. }
  50430. // Color3
  50431. serializationObject.colors3 = {};
  50432. for (name in this._colors3) {
  50433. serializationObject.colors3[name] = this._colors3[name].asArray();
  50434. }
  50435. // Color3 array
  50436. serializationObject.colors3Arrays = {};
  50437. for (name in this._colors3Arrays) {
  50438. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50439. }
  50440. // Color4
  50441. serializationObject.colors4 = {};
  50442. for (name in this._colors4) {
  50443. serializationObject.colors4[name] = this._colors4[name].asArray();
  50444. }
  50445. // Vector2
  50446. serializationObject.vectors2 = {};
  50447. for (name in this._vectors2) {
  50448. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50449. }
  50450. // Vector3
  50451. serializationObject.vectors3 = {};
  50452. for (name in this._vectors3) {
  50453. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50454. }
  50455. // Vector4
  50456. serializationObject.vectors4 = {};
  50457. for (name in this._vectors4) {
  50458. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50459. }
  50460. // Matrix
  50461. serializationObject.matrices = {};
  50462. for (name in this._matrices) {
  50463. serializationObject.matrices[name] = this._matrices[name].asArray();
  50464. }
  50465. // Matrix 3x3
  50466. serializationObject.matrices3x3 = {};
  50467. for (name in this._matrices3x3) {
  50468. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50469. }
  50470. // Matrix 2x2
  50471. serializationObject.matrices2x2 = {};
  50472. for (name in this._matrices2x2) {
  50473. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50474. }
  50475. // Vector2Array
  50476. serializationObject.vectors2Arrays = {};
  50477. for (name in this._vectors2Arrays) {
  50478. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50479. }
  50480. // Vector3Array
  50481. serializationObject.vectors3Arrays = {};
  50482. for (name in this._vectors3Arrays) {
  50483. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50484. }
  50485. return serializationObject;
  50486. };
  50487. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50488. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50489. var name;
  50490. // Texture
  50491. for (name in source.textures) {
  50492. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50493. }
  50494. // Texture arrays
  50495. for (name in source.textureArrays) {
  50496. var array = source.textureArrays[name];
  50497. var textureArray = new Array();
  50498. for (var index = 0; index < array.length; index++) {
  50499. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50500. }
  50501. material.setTextureArray(name, textureArray);
  50502. }
  50503. // Float
  50504. for (name in source.floats) {
  50505. material.setFloat(name, source.floats[name]);
  50506. }
  50507. // Float s
  50508. for (name in source.floatsArrays) {
  50509. material.setFloats(name, source.floatsArrays[name]);
  50510. }
  50511. // Color3
  50512. for (name in source.colors3) {
  50513. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50514. }
  50515. // Color3 arrays
  50516. for (name in source.colors3Arrays) {
  50517. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50518. if (i % 3 === 0) {
  50519. arr.push([num]);
  50520. }
  50521. else {
  50522. arr[arr.length - 1].push(num);
  50523. }
  50524. return arr;
  50525. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50526. material.setColor3Array(name, colors);
  50527. }
  50528. // Color4
  50529. for (name in source.colors4) {
  50530. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50531. }
  50532. // Vector2
  50533. for (name in source.vectors2) {
  50534. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50535. }
  50536. // Vector3
  50537. for (name in source.vectors3) {
  50538. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50539. }
  50540. // Vector4
  50541. for (name in source.vectors4) {
  50542. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50543. }
  50544. // Matrix
  50545. for (name in source.matrices) {
  50546. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50547. }
  50548. // Matrix 3x3
  50549. for (name in source.matrices3x3) {
  50550. material.setMatrix3x3(name, source.matrices3x3[name]);
  50551. }
  50552. // Matrix 2x2
  50553. for (name in source.matrices2x2) {
  50554. material.setMatrix2x2(name, source.matrices2x2[name]);
  50555. }
  50556. // Vector2Array
  50557. for (name in source.vectors2Arrays) {
  50558. material.setArray2(name, source.vectors2Arrays[name]);
  50559. }
  50560. // Vector3Array
  50561. for (name in source.vectors3Arrays) {
  50562. material.setArray3(name, source.vectors3Arrays[name]);
  50563. }
  50564. return material;
  50565. };
  50566. return ShaderMaterial;
  50567. }(BABYLON.Material));
  50568. BABYLON.ShaderMaterial = ShaderMaterial;
  50569. })(BABYLON || (BABYLON = {}));
  50570. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50571. var BABYLON;
  50572. (function (BABYLON) {
  50573. var GroundMesh = /** @class */ (function (_super) {
  50574. __extends(GroundMesh, _super);
  50575. function GroundMesh(name, scene) {
  50576. var _this = _super.call(this, name, scene) || this;
  50577. _this.generateOctree = false;
  50578. return _this;
  50579. }
  50580. GroundMesh.prototype.getClassName = function () {
  50581. return "GroundMesh";
  50582. };
  50583. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50584. get: function () {
  50585. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50586. },
  50587. enumerable: true,
  50588. configurable: true
  50589. });
  50590. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50591. get: function () {
  50592. return this._subdivisionsX;
  50593. },
  50594. enumerable: true,
  50595. configurable: true
  50596. });
  50597. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50598. get: function () {
  50599. return this._subdivisionsY;
  50600. },
  50601. enumerable: true,
  50602. configurable: true
  50603. });
  50604. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50605. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50606. this._subdivisionsX = chunksCount;
  50607. this._subdivisionsY = chunksCount;
  50608. this.subdivide(chunksCount);
  50609. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50610. };
  50611. /**
  50612. * Returns a height (y) value in the Worl system :
  50613. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50614. * Returns the ground y position if (x, z) are outside the ground surface.
  50615. */
  50616. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50617. var world = this.getWorldMatrix();
  50618. var invMat = BABYLON.Tmp.Matrix[5];
  50619. world.invertToRef(invMat);
  50620. var tmpVect = BABYLON.Tmp.Vector3[8];
  50621. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50622. x = tmpVect.x;
  50623. z = tmpVect.z;
  50624. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50625. return this.position.y;
  50626. }
  50627. if (!this._heightQuads || this._heightQuads.length == 0) {
  50628. this._initHeightQuads();
  50629. this._computeHeightQuads();
  50630. }
  50631. var facet = this._getFacetAt(x, z);
  50632. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50633. // return y in the World system
  50634. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50635. return tmpVect.y;
  50636. };
  50637. /**
  50638. * Returns a normalized vector (Vector3) orthogonal to the ground
  50639. * at the ground coordinates (x, z) expressed in the World system.
  50640. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50641. */
  50642. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50643. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50644. this.getNormalAtCoordinatesToRef(x, z, normal);
  50645. return normal;
  50646. };
  50647. /**
  50648. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50649. * at the ground coordinates (x, z) expressed in the World system.
  50650. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50651. * Returns the GroundMesh.
  50652. */
  50653. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50654. var world = this.getWorldMatrix();
  50655. var tmpMat = BABYLON.Tmp.Matrix[5];
  50656. world.invertToRef(tmpMat);
  50657. var tmpVect = BABYLON.Tmp.Vector3[8];
  50658. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50659. x = tmpVect.x;
  50660. z = tmpVect.z;
  50661. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50662. return this;
  50663. }
  50664. if (!this._heightQuads || this._heightQuads.length == 0) {
  50665. this._initHeightQuads();
  50666. this._computeHeightQuads();
  50667. }
  50668. var facet = this._getFacetAt(x, z);
  50669. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  50670. return this;
  50671. };
  50672. /**
  50673. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  50674. * if the ground has been updated.
  50675. * This can be used in the render loop.
  50676. * Returns the GroundMesh.
  50677. */
  50678. GroundMesh.prototype.updateCoordinateHeights = function () {
  50679. if (!this._heightQuads || this._heightQuads.length == 0) {
  50680. this._initHeightQuads();
  50681. }
  50682. this._computeHeightQuads();
  50683. return this;
  50684. };
  50685. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  50686. GroundMesh.prototype._getFacetAt = function (x, z) {
  50687. // retrieve col and row from x, z coordinates in the ground local system
  50688. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  50689. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  50690. var quad = this._heightQuads[row * this._subdivisionsX + col];
  50691. var facet;
  50692. if (z < quad.slope.x * x + quad.slope.y) {
  50693. facet = quad.facet1;
  50694. }
  50695. else {
  50696. facet = quad.facet2;
  50697. }
  50698. return facet;
  50699. };
  50700. // Creates and populates the heightMap array with "facet" elements :
  50701. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  50702. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50703. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50704. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50705. // Returns the GroundMesh.
  50706. GroundMesh.prototype._initHeightQuads = function () {
  50707. var subdivisionsX = this._subdivisionsX;
  50708. var subdivisionsY = this._subdivisionsY;
  50709. this._heightQuads = new Array();
  50710. for (var row = 0; row < subdivisionsY; row++) {
  50711. for (var col = 0; col < subdivisionsX; col++) {
  50712. 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) };
  50713. this._heightQuads[row * subdivisionsX + col] = quad;
  50714. }
  50715. }
  50716. return this;
  50717. };
  50718. // Compute each quad element values and update the the heightMap array :
  50719. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50720. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50721. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50722. // Returns the GroundMesh.
  50723. GroundMesh.prototype._computeHeightQuads = function () {
  50724. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50725. if (!positions) {
  50726. return this;
  50727. }
  50728. var v1 = BABYLON.Tmp.Vector3[3];
  50729. var v2 = BABYLON.Tmp.Vector3[2];
  50730. var v3 = BABYLON.Tmp.Vector3[1];
  50731. var v4 = BABYLON.Tmp.Vector3[0];
  50732. var v1v2 = BABYLON.Tmp.Vector3[4];
  50733. var v1v3 = BABYLON.Tmp.Vector3[5];
  50734. var v1v4 = BABYLON.Tmp.Vector3[6];
  50735. var norm1 = BABYLON.Tmp.Vector3[7];
  50736. var norm2 = BABYLON.Tmp.Vector3[8];
  50737. var i = 0;
  50738. var j = 0;
  50739. var k = 0;
  50740. var cd = 0; // 2D slope coefficient : z = cd * x + h
  50741. var h = 0;
  50742. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  50743. var d2 = 0;
  50744. var subdivisionsX = this._subdivisionsX;
  50745. var subdivisionsY = this._subdivisionsY;
  50746. for (var row = 0; row < subdivisionsY; row++) {
  50747. for (var col = 0; col < subdivisionsX; col++) {
  50748. i = col * 3;
  50749. j = row * (subdivisionsX + 1) * 3;
  50750. k = (row + 1) * (subdivisionsX + 1) * 3;
  50751. v1.x = positions[j + i];
  50752. v1.y = positions[j + i + 1];
  50753. v1.z = positions[j + i + 2];
  50754. v2.x = positions[j + i + 3];
  50755. v2.y = positions[j + i + 4];
  50756. v2.z = positions[j + i + 5];
  50757. v3.x = positions[k + i];
  50758. v3.y = positions[k + i + 1];
  50759. v3.z = positions[k + i + 2];
  50760. v4.x = positions[k + i + 3];
  50761. v4.y = positions[k + i + 4];
  50762. v4.z = positions[k + i + 5];
  50763. // 2D slope V1V4
  50764. cd = (v4.z - v1.z) / (v4.x - v1.x);
  50765. h = v1.z - cd * v1.x; // v1 belongs to the slope
  50766. // facet equations :
  50767. // we compute each facet normal vector
  50768. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  50769. // we compute the value d by applying the equation to v1 which belongs to the plane
  50770. // then we store the facet equation in a Vector4
  50771. v2.subtractToRef(v1, v1v2);
  50772. v3.subtractToRef(v1, v1v3);
  50773. v4.subtractToRef(v1, v1v4);
  50774. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  50775. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  50776. norm1.normalize();
  50777. norm2.normalize();
  50778. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  50779. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  50780. var quad = this._heightQuads[row * subdivisionsX + col];
  50781. quad.slope.copyFromFloats(cd, h);
  50782. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  50783. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  50784. }
  50785. }
  50786. return this;
  50787. };
  50788. GroundMesh.prototype.serialize = function (serializationObject) {
  50789. _super.prototype.serialize.call(this, serializationObject);
  50790. serializationObject.subdivisionsX = this._subdivisionsX;
  50791. serializationObject.subdivisionsY = this._subdivisionsY;
  50792. serializationObject.minX = this._minX;
  50793. serializationObject.maxX = this._maxX;
  50794. serializationObject.minZ = this._minZ;
  50795. serializationObject.maxZ = this._maxZ;
  50796. serializationObject.width = this._width;
  50797. serializationObject.height = this._height;
  50798. };
  50799. GroundMesh.Parse = function (parsedMesh, scene) {
  50800. var result = new GroundMesh(parsedMesh.name, scene);
  50801. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  50802. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  50803. result._minX = parsedMesh.minX;
  50804. result._maxX = parsedMesh.maxX;
  50805. result._minZ = parsedMesh.minZ;
  50806. result._maxZ = parsedMesh.maxZ;
  50807. result._width = parsedMesh.width;
  50808. result._height = parsedMesh.height;
  50809. return result;
  50810. };
  50811. return GroundMesh;
  50812. }(BABYLON.Mesh));
  50813. BABYLON.GroundMesh = GroundMesh;
  50814. })(BABYLON || (BABYLON = {}));
  50815. //# sourceMappingURL=babylon.groundMesh.js.map
  50816. var BABYLON;
  50817. (function (BABYLON) {
  50818. /**
  50819. * Creates an instance based on a source mesh.
  50820. */
  50821. var InstancedMesh = /** @class */ (function (_super) {
  50822. __extends(InstancedMesh, _super);
  50823. function InstancedMesh(name, source) {
  50824. var _this = _super.call(this, name, source.getScene()) || this;
  50825. source.instances.push(_this);
  50826. _this._sourceMesh = source;
  50827. _this.position.copyFrom(source.position);
  50828. _this.rotation.copyFrom(source.rotation);
  50829. _this.scaling.copyFrom(source.scaling);
  50830. if (source.rotationQuaternion) {
  50831. _this.rotationQuaternion = source.rotationQuaternion.clone();
  50832. }
  50833. _this.infiniteDistance = source.infiniteDistance;
  50834. _this.setPivotMatrix(source.getPivotMatrix());
  50835. _this.refreshBoundingInfo();
  50836. _this._syncSubMeshes();
  50837. return _this;
  50838. }
  50839. /**
  50840. * Returns the string "InstancedMesh".
  50841. */
  50842. InstancedMesh.prototype.getClassName = function () {
  50843. return "InstancedMesh";
  50844. };
  50845. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  50846. // Methods
  50847. get: function () {
  50848. return this._sourceMesh.receiveShadows;
  50849. },
  50850. enumerable: true,
  50851. configurable: true
  50852. });
  50853. Object.defineProperty(InstancedMesh.prototype, "material", {
  50854. get: function () {
  50855. return this._sourceMesh.material;
  50856. },
  50857. enumerable: true,
  50858. configurable: true
  50859. });
  50860. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  50861. get: function () {
  50862. return this._sourceMesh.visibility;
  50863. },
  50864. enumerable: true,
  50865. configurable: true
  50866. });
  50867. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  50868. get: function () {
  50869. return this._sourceMesh.skeleton;
  50870. },
  50871. enumerable: true,
  50872. configurable: true
  50873. });
  50874. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  50875. get: function () {
  50876. return this._sourceMesh.renderingGroupId;
  50877. },
  50878. enumerable: true,
  50879. configurable: true
  50880. });
  50881. /**
  50882. * Returns the total number of vertices (integer).
  50883. */
  50884. InstancedMesh.prototype.getTotalVertices = function () {
  50885. return this._sourceMesh.getTotalVertices();
  50886. };
  50887. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  50888. get: function () {
  50889. return this._sourceMesh;
  50890. },
  50891. enumerable: true,
  50892. configurable: true
  50893. });
  50894. /**
  50895. * Is this node ready to be used/rendered
  50896. * @return {boolean} is it ready
  50897. */
  50898. InstancedMesh.prototype.isReady = function () {
  50899. return this._sourceMesh.isReady(true);
  50900. };
  50901. /**
  50902. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  50903. */
  50904. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  50905. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  50906. };
  50907. /**
  50908. * Sets the vertex data of the mesh geometry for the requested `kind`.
  50909. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  50910. * The `data` are either a numeric array either a Float32Array.
  50911. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  50912. * 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).
  50913. * Note that a new underlying VertexBuffer object is created each call.
  50914. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  50915. *
  50916. * Possible `kind` values :
  50917. * - BABYLON.VertexBuffer.PositionKind
  50918. * - BABYLON.VertexBuffer.UVKind
  50919. * - BABYLON.VertexBuffer.UV2Kind
  50920. * - BABYLON.VertexBuffer.UV3Kind
  50921. * - BABYLON.VertexBuffer.UV4Kind
  50922. * - BABYLON.VertexBuffer.UV5Kind
  50923. * - BABYLON.VertexBuffer.UV6Kind
  50924. * - BABYLON.VertexBuffer.ColorKind
  50925. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50926. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50927. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50928. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50929. *
  50930. * Returns the Mesh.
  50931. */
  50932. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  50933. if (this.sourceMesh) {
  50934. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  50935. }
  50936. return this.sourceMesh;
  50937. };
  50938. /**
  50939. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  50940. * If the mesh has no geometry, it is simply returned as it is.
  50941. * The `data` are either a numeric array either a Float32Array.
  50942. * No new underlying VertexBuffer object is created.
  50943. * 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.
  50944. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  50945. *
  50946. * Possible `kind` values :
  50947. * - BABYLON.VertexBuffer.PositionKind
  50948. * - BABYLON.VertexBuffer.UVKind
  50949. * - BABYLON.VertexBuffer.UV2Kind
  50950. * - BABYLON.VertexBuffer.UV3Kind
  50951. * - BABYLON.VertexBuffer.UV4Kind
  50952. * - BABYLON.VertexBuffer.UV5Kind
  50953. * - BABYLON.VertexBuffer.UV6Kind
  50954. * - BABYLON.VertexBuffer.ColorKind
  50955. * - BABYLON.VertexBuffer.MatricesIndicesKind
  50956. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  50957. * - BABYLON.VertexBuffer.MatricesWeightsKind
  50958. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  50959. *
  50960. * Returns the Mesh.
  50961. */
  50962. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  50963. if (this.sourceMesh) {
  50964. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  50965. }
  50966. return this.sourceMesh;
  50967. };
  50968. /**
  50969. * Sets the mesh indices.
  50970. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  50971. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  50972. * This method creates a new index buffer each call.
  50973. * Returns the Mesh.
  50974. */
  50975. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  50976. if (totalVertices === void 0) { totalVertices = null; }
  50977. if (this.sourceMesh) {
  50978. this.sourceMesh.setIndices(indices, totalVertices);
  50979. }
  50980. return this.sourceMesh;
  50981. };
  50982. /**
  50983. * Boolean : True if the mesh owns the requested kind of data.
  50984. */
  50985. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  50986. return this._sourceMesh.isVerticesDataPresent(kind);
  50987. };
  50988. /**
  50989. * Returns an array of indices (IndicesArray).
  50990. */
  50991. InstancedMesh.prototype.getIndices = function () {
  50992. return this._sourceMesh.getIndices();
  50993. };
  50994. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  50995. get: function () {
  50996. return this._sourceMesh._positions;
  50997. },
  50998. enumerable: true,
  50999. configurable: true
  51000. });
  51001. /**
  51002. * Sets a new updated BoundingInfo to the mesh.
  51003. * Returns the mesh.
  51004. */
  51005. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51006. var meshBB = this._sourceMesh.getBoundingInfo();
  51007. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51008. this._updateBoundingInfo();
  51009. return this;
  51010. };
  51011. InstancedMesh.prototype._preActivate = function () {
  51012. if (this._currentLOD) {
  51013. this._currentLOD._preActivate();
  51014. }
  51015. return this;
  51016. };
  51017. InstancedMesh.prototype._activate = function (renderId) {
  51018. if (this._currentLOD) {
  51019. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51020. }
  51021. return this;
  51022. };
  51023. /**
  51024. * Returns the current associated LOD AbstractMesh.
  51025. */
  51026. InstancedMesh.prototype.getLOD = function (camera) {
  51027. if (!camera) {
  51028. return this;
  51029. }
  51030. var boundingInfo = this.getBoundingInfo();
  51031. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51032. if (this._currentLOD === this.sourceMesh) {
  51033. return this;
  51034. }
  51035. return this._currentLOD;
  51036. };
  51037. InstancedMesh.prototype._syncSubMeshes = function () {
  51038. this.releaseSubMeshes();
  51039. if (this._sourceMesh.subMeshes) {
  51040. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51041. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51042. }
  51043. }
  51044. return this;
  51045. };
  51046. InstancedMesh.prototype._generatePointsArray = function () {
  51047. return this._sourceMesh._generatePointsArray();
  51048. };
  51049. /**
  51050. * Creates a new InstancedMesh from the current mesh.
  51051. * - name (string) : the cloned mesh name
  51052. * - newParent (optional Node) : the optional Node to parent the clone to.
  51053. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51054. *
  51055. * Returns the clone.
  51056. */
  51057. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51058. var result = this._sourceMesh.createInstance(name);
  51059. // Deep copy
  51060. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51061. // Bounding info
  51062. this.refreshBoundingInfo();
  51063. // Parent
  51064. if (newParent) {
  51065. result.parent = newParent;
  51066. }
  51067. if (!doNotCloneChildren) {
  51068. // Children
  51069. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51070. var mesh = this.getScene().meshes[index];
  51071. if (mesh.parent === this) {
  51072. mesh.clone(mesh.name, result);
  51073. }
  51074. }
  51075. }
  51076. result.computeWorldMatrix(true);
  51077. return result;
  51078. };
  51079. /**
  51080. * Disposes the InstancedMesh.
  51081. * Returns nothing.
  51082. */
  51083. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51084. // Remove from mesh
  51085. var index = this._sourceMesh.instances.indexOf(this);
  51086. this._sourceMesh.instances.splice(index, 1);
  51087. _super.prototype.dispose.call(this, doNotRecurse);
  51088. };
  51089. return InstancedMesh;
  51090. }(BABYLON.AbstractMesh));
  51091. BABYLON.InstancedMesh = InstancedMesh;
  51092. })(BABYLON || (BABYLON = {}));
  51093. //# sourceMappingURL=babylon.instancedMesh.js.map
  51094. var BABYLON;
  51095. (function (BABYLON) {
  51096. var LinesMesh = /** @class */ (function (_super) {
  51097. __extends(LinesMesh, _super);
  51098. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51099. if (scene === void 0) { scene = null; }
  51100. if (parent === void 0) { parent = null; }
  51101. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51102. _this.useVertexColor = useVertexColor;
  51103. _this.useVertexAlpha = useVertexAlpha;
  51104. _this.color = new BABYLON.Color3(1, 1, 1);
  51105. _this.alpha = 1;
  51106. if (source) {
  51107. _this.color = source.color.clone();
  51108. _this.alpha = source.alpha;
  51109. _this.useVertexColor = source.useVertexColor;
  51110. _this.useVertexAlpha = source.useVertexAlpha;
  51111. }
  51112. _this._intersectionThreshold = 0.1;
  51113. var defines = [];
  51114. var options = {
  51115. attributes: [BABYLON.VertexBuffer.PositionKind],
  51116. uniforms: ["world", "viewProjection"],
  51117. needAlphaBlending: true,
  51118. defines: defines
  51119. };
  51120. if (useVertexAlpha === false) {
  51121. options.needAlphaBlending = false;
  51122. }
  51123. if (!useVertexColor) {
  51124. options.uniforms.push("color");
  51125. }
  51126. else {
  51127. options.defines.push("#define VERTEXCOLOR");
  51128. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51129. }
  51130. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51131. return _this;
  51132. }
  51133. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51134. /**
  51135. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51136. * This margin is expressed in world space coordinates, so its value may vary.
  51137. * Default value is 0.1
  51138. * @returns the intersection Threshold value.
  51139. */
  51140. get: function () {
  51141. return this._intersectionThreshold;
  51142. },
  51143. /**
  51144. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51145. * This margin is expressed in world space coordinates, so its value may vary.
  51146. * @param value the new threshold to apply
  51147. */
  51148. set: function (value) {
  51149. if (this._intersectionThreshold === value) {
  51150. return;
  51151. }
  51152. this._intersectionThreshold = value;
  51153. if (this.geometry) {
  51154. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  51155. }
  51156. },
  51157. enumerable: true,
  51158. configurable: true
  51159. });
  51160. /**
  51161. * Returns the string "LineMesh"
  51162. */
  51163. LinesMesh.prototype.getClassName = function () {
  51164. return "LinesMesh";
  51165. };
  51166. Object.defineProperty(LinesMesh.prototype, "material", {
  51167. get: function () {
  51168. return this._colorShader;
  51169. },
  51170. set: function (value) {
  51171. // Do nothing
  51172. },
  51173. enumerable: true,
  51174. configurable: true
  51175. });
  51176. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  51177. get: function () {
  51178. return false;
  51179. },
  51180. enumerable: true,
  51181. configurable: true
  51182. });
  51183. LinesMesh.prototype.createInstance = function (name) {
  51184. throw new Error("LinesMeshes do not support createInstance.");
  51185. };
  51186. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  51187. if (!this._geometry) {
  51188. return this;
  51189. }
  51190. // VBOs
  51191. this._geometry._bind(this._colorShader.getEffect());
  51192. // Color
  51193. if (!this.useVertexColor) {
  51194. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  51195. }
  51196. return this;
  51197. };
  51198. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  51199. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  51200. return this;
  51201. }
  51202. var engine = this.getScene().getEngine();
  51203. // Draw order
  51204. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  51205. return this;
  51206. };
  51207. LinesMesh.prototype.dispose = function (doNotRecurse) {
  51208. this._colorShader.dispose();
  51209. _super.prototype.dispose.call(this, doNotRecurse);
  51210. };
  51211. /**
  51212. * Returns a new LineMesh object cloned from the current one.
  51213. */
  51214. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51215. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  51216. };
  51217. return LinesMesh;
  51218. }(BABYLON.Mesh));
  51219. BABYLON.LinesMesh = LinesMesh;
  51220. })(BABYLON || (BABYLON = {}));
  51221. //# sourceMappingURL=babylon.linesMesh.js.map
  51222. var BABYLON;
  51223. (function (BABYLON) {
  51224. var MeshBuilder = /** @class */ (function () {
  51225. function MeshBuilder() {
  51226. }
  51227. MeshBuilder.updateSideOrientation = function (orientation) {
  51228. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  51229. return BABYLON.Mesh.DOUBLESIDE;
  51230. }
  51231. if (orientation === undefined || orientation === null) {
  51232. return BABYLON.Mesh.FRONTSIDE;
  51233. }
  51234. return orientation;
  51235. };
  51236. /**
  51237. * Creates a box mesh.
  51238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  51239. * The parameter `size` sets the size (float) of each box side (default 1).
  51240. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  51241. * 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).
  51242. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51244. * 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).
  51245. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51246. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51247. */
  51248. MeshBuilder.CreateBox = function (name, options, scene) {
  51249. if (scene === void 0) { scene = null; }
  51250. var box = new BABYLON.Mesh(name, scene);
  51251. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51252. box._originalBuilderSideOrientation = options.sideOrientation;
  51253. var vertexData = BABYLON.VertexData.CreateBox(options);
  51254. vertexData.applyToMesh(box, options.updatable);
  51255. return box;
  51256. };
  51257. /**
  51258. * Creates a sphere mesh.
  51259. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51260. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51261. * 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`).
  51262. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51263. * 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
  51264. * 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).
  51265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51266. * 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).
  51267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51269. */
  51270. MeshBuilder.CreateSphere = function (name, options, scene) {
  51271. var sphere = new BABYLON.Mesh(name, scene);
  51272. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51273. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51274. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51275. vertexData.applyToMesh(sphere, options.updatable);
  51276. return sphere;
  51277. };
  51278. /**
  51279. * Creates a plane polygonal mesh. By default, this is a disc.
  51280. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51281. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51282. * 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.
  51283. * 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
  51284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51285. * 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).
  51286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51288. */
  51289. MeshBuilder.CreateDisc = function (name, options, scene) {
  51290. if (scene === void 0) { scene = null; }
  51291. var disc = new BABYLON.Mesh(name, scene);
  51292. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51293. disc._originalBuilderSideOrientation = options.sideOrientation;
  51294. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51295. vertexData.applyToMesh(disc, options.updatable);
  51296. return disc;
  51297. };
  51298. /**
  51299. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51301. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51302. * 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`).
  51303. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51304. * 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.
  51305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51306. * 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).
  51307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51309. */
  51310. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51311. var sphere = new BABYLON.Mesh(name, scene);
  51312. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51313. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51314. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51315. vertexData.applyToMesh(sphere, options.updatable);
  51316. return sphere;
  51317. };
  51318. ;
  51319. /**
  51320. * Creates a ribbon mesh.
  51321. * 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.
  51322. *
  51323. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51324. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51325. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51326. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  51327. * 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.
  51328. * 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.
  51329. * 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
  51330. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51331. * 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).
  51332. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51333. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51334. * 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.
  51335. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  51336. * 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
  51337. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  51338. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  51339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51340. */
  51341. MeshBuilder.CreateRibbon = function (name, options, scene) {
  51342. if (scene === void 0) { scene = null; }
  51343. var pathArray = options.pathArray;
  51344. var closeArray = options.closeArray;
  51345. var closePath = options.closePath;
  51346. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51347. var instance = options.instance;
  51348. var updatable = options.updatable;
  51349. if (instance) {
  51350. // positionFunction : ribbon case
  51351. // only pathArray and sideOrientation parameters are taken into account for positions update
  51352. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  51353. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  51354. var positionFunction = function (positions) {
  51355. var minlg = pathArray[0].length;
  51356. var i = 0;
  51357. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  51358. for (var si = 1; si <= ns; si++) {
  51359. for (var p = 0; p < pathArray.length; p++) {
  51360. var path = pathArray[p];
  51361. var l = path.length;
  51362. minlg = (minlg < l) ? minlg : l;
  51363. var j = 0;
  51364. while (j < minlg) {
  51365. positions[i] = path[j].x;
  51366. positions[i + 1] = path[j].y;
  51367. positions[i + 2] = path[j].z;
  51368. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  51369. BABYLON.Tmp.Vector3[0].x = path[j].x;
  51370. }
  51371. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  51372. BABYLON.Tmp.Vector3[1].x = path[j].x;
  51373. }
  51374. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  51375. BABYLON.Tmp.Vector3[0].y = path[j].y;
  51376. }
  51377. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  51378. BABYLON.Tmp.Vector3[1].y = path[j].y;
  51379. }
  51380. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  51381. BABYLON.Tmp.Vector3[0].z = path[j].z;
  51382. }
  51383. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  51384. BABYLON.Tmp.Vector3[1].z = path[j].z;
  51385. }
  51386. j++;
  51387. i += 3;
  51388. }
  51389. if (instance._closePath) {
  51390. positions[i] = path[0].x;
  51391. positions[i + 1] = path[0].y;
  51392. positions[i + 2] = path[0].z;
  51393. i += 3;
  51394. }
  51395. }
  51396. }
  51397. };
  51398. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51399. positionFunction(positions);
  51400. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  51401. instance._boundingInfo.update(instance._worldMatrix);
  51402. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51403. if (options.colors) {
  51404. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51405. for (var c = 0; c < options.colors.length; c++) {
  51406. colors[c * 4] = options.colors[c].r;
  51407. colors[c * 4 + 1] = options.colors[c].g;
  51408. colors[c * 4 + 2] = options.colors[c].b;
  51409. colors[c * 4 + 3] = options.colors[c].a;
  51410. }
  51411. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  51412. }
  51413. if (options.uvs) {
  51414. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51415. for (var i = 0; i < options.uvs.length; i++) {
  51416. uvs[i * 2] = options.uvs[i].x;
  51417. uvs[i * 2 + 1] = options.uvs[i].y;
  51418. }
  51419. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  51420. }
  51421. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  51422. var indices = instance.getIndices();
  51423. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51424. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  51425. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  51426. if (instance._closePath) {
  51427. var indexFirst = 0;
  51428. var indexLast = 0;
  51429. for (var p = 0; p < pathArray.length; p++) {
  51430. indexFirst = instance._idx[p] * 3;
  51431. if (p + 1 < pathArray.length) {
  51432. indexLast = (instance._idx[p + 1] - 1) * 3;
  51433. }
  51434. else {
  51435. indexLast = normals.length - 3;
  51436. }
  51437. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51438. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51439. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51440. normals[indexLast] = normals[indexFirst];
  51441. normals[indexLast + 1] = normals[indexFirst + 1];
  51442. normals[indexLast + 2] = normals[indexFirst + 2];
  51443. }
  51444. }
  51445. if (!(instance.areNormalsFrozen)) {
  51446. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51447. }
  51448. }
  51449. return instance;
  51450. }
  51451. else {
  51452. var ribbon = new BABYLON.Mesh(name, scene);
  51453. ribbon._originalBuilderSideOrientation = sideOrientation;
  51454. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51455. if (closePath) {
  51456. ribbon._idx = vertexData._idx;
  51457. }
  51458. ribbon._closePath = closePath;
  51459. ribbon._closeArray = closeArray;
  51460. vertexData.applyToMesh(ribbon, updatable);
  51461. return ribbon;
  51462. }
  51463. };
  51464. /**
  51465. * Creates a cylinder or a cone mesh.
  51466. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51467. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51468. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51469. * 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.
  51470. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51471. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51472. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51473. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51474. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51475. * 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).
  51476. * 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
  51477. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51478. * 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
  51479. * 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.
  51480. * If `enclose` is false, a ring surface is one element.
  51481. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51482. * 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
  51483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51484. * 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).
  51485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51487. */
  51488. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51489. var cylinder = new BABYLON.Mesh(name, scene);
  51490. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51491. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51492. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51493. vertexData.applyToMesh(cylinder, options.updatable);
  51494. return cylinder;
  51495. };
  51496. /**
  51497. * Creates a torus mesh.
  51498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51499. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51500. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51501. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51503. * 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).
  51504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51506. */
  51507. MeshBuilder.CreateTorus = function (name, options, scene) {
  51508. var torus = new BABYLON.Mesh(name, scene);
  51509. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51510. torus._originalBuilderSideOrientation = options.sideOrientation;
  51511. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51512. vertexData.applyToMesh(torus, options.updatable);
  51513. return torus;
  51514. };
  51515. /**
  51516. * Creates a torus knot mesh.
  51517. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51518. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51519. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51520. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51521. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51522. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51523. * 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).
  51524. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51526. */
  51527. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51528. var torusKnot = new BABYLON.Mesh(name, scene);
  51529. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51530. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51531. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51532. vertexData.applyToMesh(torusKnot, options.updatable);
  51533. return torusKnot;
  51534. };
  51535. /**
  51536. * Creates a line system mesh.
  51537. * A line system is a pool of many lines gathered in a single mesh.
  51538. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51539. * 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.
  51540. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51541. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51542. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  51543. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51544. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51545. * 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
  51546. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51548. */
  51549. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51550. var instance = options.instance;
  51551. var lines = options.lines;
  51552. var colors = options.colors;
  51553. if (instance) {
  51554. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51555. var vertexColor;
  51556. var lineColors;
  51557. if (colors) {
  51558. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51559. }
  51560. var i = 0;
  51561. var c = 0;
  51562. for (var l = 0; l < lines.length; l++) {
  51563. var points = lines[l];
  51564. for (var p = 0; p < points.length; p++) {
  51565. positions[i] = points[p].x;
  51566. positions[i + 1] = points[p].y;
  51567. positions[i + 2] = points[p].z;
  51568. if (colors && vertexColor) {
  51569. lineColors = colors[l];
  51570. vertexColor[c] = lineColors[p].r;
  51571. vertexColor[c + 1] = lineColors[p].g;
  51572. vertexColor[c + 2] = lineColors[p].b;
  51573. vertexColor[c + 3] = lineColors[p].a;
  51574. c += 4;
  51575. }
  51576. i += 3;
  51577. }
  51578. }
  51579. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51580. if (colors && vertexColor) {
  51581. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51582. }
  51583. return instance;
  51584. }
  51585. // line system creation
  51586. var useVertexColor = (colors) ? true : false;
  51587. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51588. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51589. vertexData.applyToMesh(lineSystem, options.updatable);
  51590. return lineSystem;
  51591. };
  51592. /**
  51593. * Creates a line mesh.
  51594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51595. * 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.
  51596. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51597. * The parameter `points` is an array successive Vector3.
  51598. * 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
  51599. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51600. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51601. * When updating an instance, remember that only point positions can change, not the number of points.
  51602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51603. */
  51604. MeshBuilder.CreateLines = function (name, options, scene) {
  51605. if (scene === void 0) { scene = null; }
  51606. var colors = (options.colors) ? [options.colors] : null;
  51607. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51608. return lines;
  51609. };
  51610. /**
  51611. * Creates a dashed line mesh.
  51612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51613. * 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.
  51614. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51615. * The parameter `points` is an array successive Vector3.
  51616. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51617. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51618. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51619. * 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
  51620. * When updating an instance, remember that only point positions can change, not the number of points.
  51621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51622. */
  51623. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51624. if (scene === void 0) { scene = null; }
  51625. var points = options.points;
  51626. var instance = options.instance;
  51627. var gapSize = options.gapSize || 1;
  51628. var dashSize = options.dashSize || 3;
  51629. if (instance) {
  51630. var positionFunction = function (positions) {
  51631. var curvect = BABYLON.Vector3.Zero();
  51632. var nbSeg = positions.length / 6;
  51633. var lg = 0;
  51634. var nb = 0;
  51635. var shft = 0;
  51636. var dashshft = 0;
  51637. var curshft = 0;
  51638. var p = 0;
  51639. var i = 0;
  51640. var j = 0;
  51641. for (i = 0; i < points.length - 1; i++) {
  51642. points[i + 1].subtractToRef(points[i], curvect);
  51643. lg += curvect.length();
  51644. }
  51645. shft = lg / nbSeg;
  51646. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51647. for (i = 0; i < points.length - 1; i++) {
  51648. points[i + 1].subtractToRef(points[i], curvect);
  51649. nb = Math.floor(curvect.length() / shft);
  51650. curvect.normalize();
  51651. j = 0;
  51652. while (j < nb && p < positions.length) {
  51653. curshft = shft * j;
  51654. positions[p] = points[i].x + curshft * curvect.x;
  51655. positions[p + 1] = points[i].y + curshft * curvect.y;
  51656. positions[p + 2] = points[i].z + curshft * curvect.z;
  51657. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51658. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51659. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51660. p += 6;
  51661. j++;
  51662. }
  51663. }
  51664. while (p < positions.length) {
  51665. positions[p] = points[i].x;
  51666. positions[p + 1] = points[i].y;
  51667. positions[p + 2] = points[i].z;
  51668. p += 3;
  51669. }
  51670. };
  51671. instance.updateMeshPositions(positionFunction, false);
  51672. return instance;
  51673. }
  51674. // dashed lines creation
  51675. var dashedLines = new BABYLON.LinesMesh(name, scene);
  51676. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  51677. vertexData.applyToMesh(dashedLines, options.updatable);
  51678. dashedLines.dashSize = dashSize;
  51679. dashedLines.gapSize = gapSize;
  51680. return dashedLines;
  51681. };
  51682. /**
  51683. * Creates an extruded shape mesh.
  51684. * 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.
  51685. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  51686. *
  51687. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51688. * 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
  51689. * extruded along the Z axis.
  51690. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51691. * 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.
  51692. * The parameter `scale` (float, default 1) is the value to scale the shape.
  51693. * 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
  51694. * 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
  51695. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51697. * 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).
  51698. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51699. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51701. */
  51702. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  51703. if (scene === void 0) { scene = null; }
  51704. var path = options.path;
  51705. var shape = options.shape;
  51706. var scale = options.scale || 1;
  51707. var rotation = options.rotation || 0;
  51708. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51709. var updatable = options.updatable;
  51710. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51711. var instance = options.instance || null;
  51712. var invertUV = options.invertUV || false;
  51713. 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);
  51714. };
  51715. /**
  51716. * Creates an custom extruded shape mesh.
  51717. * 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.
  51718. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  51719. *
  51720. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51721. * 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
  51722. * extruded along the Z axis.
  51723. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51724. * 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
  51725. * and the distance of this point from the begining of the path :
  51726. * ```javascript
  51727. * var rotationFunction = function(i, distance) {
  51728. * // do things
  51729. * return rotationValue; }
  51730. * ```
  51731. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  51732. * 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
  51733. * and the distance of this point from the begining of the path :
  51734. * ```javascript
  51735. * var scaleFunction = function(i, distance) {
  51736. * // do things
  51737. * return scaleValue;}
  51738. * ```
  51739. * It must returns a float value that will be the scale value applied to the shape on each path point.
  51740. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  51741. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  51742. * 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
  51743. * 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
  51744. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51746. * 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).
  51747. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51748. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51750. */
  51751. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  51752. var path = options.path;
  51753. var shape = options.shape;
  51754. var scaleFunction = options.scaleFunction || (function () { return 1; });
  51755. var rotationFunction = options.rotationFunction || (function () { return 0; });
  51756. var ribbonCloseArray = options.ribbonCloseArray || false;
  51757. var ribbonClosePath = options.ribbonClosePath || false;
  51758. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51759. var updatable = options.updatable;
  51760. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51761. var instance = options.instance;
  51762. var invertUV = options.invertUV || false;
  51763. 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);
  51764. };
  51765. /**
  51766. * Creates lathe mesh.
  51767. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  51768. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  51769. *
  51770. * 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
  51771. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  51772. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  51773. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  51774. * 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.
  51775. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  51776. * 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
  51777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51778. * 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).
  51779. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51780. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51782. */
  51783. MeshBuilder.CreateLathe = function (name, options, scene) {
  51784. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  51785. var closed = (options.closed === undefined) ? true : options.closed;
  51786. var shape = options.shape;
  51787. var radius = options.radius || 1;
  51788. var tessellation = options.tessellation || 64;
  51789. var updatable = options.updatable;
  51790. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51791. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51792. var pi2 = Math.PI * 2;
  51793. var paths = new Array();
  51794. var invertUV = options.invertUV || false;
  51795. var i = 0;
  51796. var p = 0;
  51797. var step = pi2 / tessellation * arc;
  51798. var rotated;
  51799. var path = new Array();
  51800. ;
  51801. for (i = 0; i <= tessellation; i++) {
  51802. var path = [];
  51803. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  51804. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  51805. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  51806. }
  51807. for (p = 0; p < shape.length; p++) {
  51808. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  51809. path.push(rotated);
  51810. }
  51811. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  51812. 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));
  51813. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  51814. }
  51815. paths.push(path);
  51816. }
  51817. // lathe ribbon
  51818. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51819. return lathe;
  51820. };
  51821. /**
  51822. * Creates a plane mesh.
  51823. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51824. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  51825. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  51826. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  51827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51828. * 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).
  51829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51831. */
  51832. MeshBuilder.CreatePlane = function (name, options, scene) {
  51833. var plane = new BABYLON.Mesh(name, scene);
  51834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51835. plane._originalBuilderSideOrientation = options.sideOrientation;
  51836. var vertexData = BABYLON.VertexData.CreatePlane(options);
  51837. vertexData.applyToMesh(plane, options.updatable);
  51838. if (options.sourcePlane) {
  51839. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  51840. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  51841. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  51842. plane.rotate(vectorProduct, product);
  51843. }
  51844. return plane;
  51845. };
  51846. /**
  51847. * Creates a ground mesh.
  51848. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51849. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  51850. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  51851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51852. */
  51853. MeshBuilder.CreateGround = function (name, options, scene) {
  51854. var ground = new BABYLON.GroundMesh(name, scene);
  51855. ground._setReady(false);
  51856. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  51857. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  51858. ground._width = options.width || 1;
  51859. ground._height = options.height || 1;
  51860. ground._maxX = ground._width / 2;
  51861. ground._maxZ = ground._height / 2;
  51862. ground._minX = -ground._maxX;
  51863. ground._minZ = -ground._maxZ;
  51864. var vertexData = BABYLON.VertexData.CreateGround(options);
  51865. vertexData.applyToMesh(ground, options.updatable);
  51866. ground._setReady(true);
  51867. return ground;
  51868. };
  51869. /**
  51870. * Creates a tiled ground mesh.
  51871. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  51872. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  51873. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  51874. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  51875. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  51876. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  51877. * numbers of subdivisions on the ground width and height of each tile.
  51878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51879. */
  51880. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  51881. var tiledGround = new BABYLON.Mesh(name, scene);
  51882. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  51883. vertexData.applyToMesh(tiledGround, options.updatable);
  51884. return tiledGround;
  51885. };
  51886. /**
  51887. * Creates a ground mesh from a height map.
  51888. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  51889. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  51890. * The parameter `url` sets the URL of the height map image resource.
  51891. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  51892. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  51893. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  51894. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  51895. * 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.
  51896. * 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).
  51897. * This function is passed the newly built mesh :
  51898. * ```javascript
  51899. * function(mesh) { // do things
  51900. * return; }
  51901. * ```
  51902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51903. */
  51904. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  51905. var width = options.width || 10.0;
  51906. var height = options.height || 10.0;
  51907. var subdivisions = options.subdivisions || 1 | 0;
  51908. var minHeight = options.minHeight || 0.0;
  51909. var maxHeight = options.maxHeight || 1.0;
  51910. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  51911. var updatable = options.updatable;
  51912. var onReady = options.onReady;
  51913. var ground = new BABYLON.GroundMesh(name, scene);
  51914. ground._subdivisionsX = subdivisions;
  51915. ground._subdivisionsY = subdivisions;
  51916. ground._width = width;
  51917. ground._height = height;
  51918. ground._maxX = ground._width / 2.0;
  51919. ground._maxZ = ground._height / 2.0;
  51920. ground._minX = -ground._maxX;
  51921. ground._minZ = -ground._maxZ;
  51922. ground._setReady(false);
  51923. var onload = function (img) {
  51924. // Getting height map data
  51925. var canvas = document.createElement("canvas");
  51926. var context = canvas.getContext("2d");
  51927. if (!context) {
  51928. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  51929. }
  51930. if (scene.isDisposed) {
  51931. return;
  51932. }
  51933. var bufferWidth = img.width;
  51934. var bufferHeight = img.height;
  51935. canvas.width = bufferWidth;
  51936. canvas.height = bufferHeight;
  51937. context.drawImage(img, 0, 0);
  51938. // Create VertexData from map data
  51939. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  51940. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  51941. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  51942. width: width, height: height,
  51943. subdivisions: subdivisions,
  51944. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  51945. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  51946. });
  51947. vertexData.applyToMesh(ground, updatable);
  51948. ground._setReady(true);
  51949. //execute ready callback, if set
  51950. if (onReady) {
  51951. onReady(ground);
  51952. }
  51953. };
  51954. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  51955. return ground;
  51956. };
  51957. /**
  51958. * Creates a polygon mesh.
  51959. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  51960. * 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.
  51961. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51963. * 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).
  51964. * Remember you can only change the shape positions, not their number when updating a polygon.
  51965. */
  51966. MeshBuilder.CreatePolygon = function (name, options, scene) {
  51967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51968. var shape = options.shape;
  51969. var holes = options.holes || [];
  51970. var depth = options.depth || 0;
  51971. var contours = [];
  51972. var hole = [];
  51973. for (var i = 0; i < shape.length; i++) {
  51974. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  51975. }
  51976. var epsilon = 0.00000001;
  51977. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  51978. contours.pop();
  51979. }
  51980. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  51981. for (var hNb = 0; hNb < holes.length; hNb++) {
  51982. hole = [];
  51983. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  51984. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  51985. }
  51986. polygonTriangulation.addHole(hole);
  51987. }
  51988. var polygon = polygonTriangulation.build(options.updatable, depth);
  51989. polygon._originalBuilderSideOrientation = options.sideOrientation;
  51990. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  51991. vertexData.applyToMesh(polygon, options.updatable);
  51992. return polygon;
  51993. };
  51994. ;
  51995. /**
  51996. * Creates an extruded polygon mesh, with depth in the Y direction.
  51997. * 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).
  51998. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51999. */
  52000. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52001. return MeshBuilder.CreatePolygon(name, options, scene);
  52002. };
  52003. ;
  52004. /**
  52005. * Creates a tube mesh.
  52006. * 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.
  52007. *
  52008. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52009. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52010. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52011. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52012. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52013. * 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.
  52014. * It must return a radius value (positive float) :
  52015. * ```javascript
  52016. * var radiusFunction = function(i, distance) {
  52017. * // do things
  52018. * return radius; }
  52019. * ```
  52020. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52021. * 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
  52022. * 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
  52023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52024. * 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).
  52025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52026. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52028. */
  52029. MeshBuilder.CreateTube = function (name, options, scene) {
  52030. var path = options.path;
  52031. var instance = options.instance;
  52032. var radius = 1.0;
  52033. if (instance) {
  52034. radius = instance.radius;
  52035. }
  52036. if (options.radius !== undefined) {
  52037. radius = options.radius;
  52038. }
  52039. ;
  52040. var tessellation = options.tessellation || 64 | 0;
  52041. var radiusFunction = options.radiusFunction || null;
  52042. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52043. var invertUV = options.invertUV || false;
  52044. var updatable = options.updatable;
  52045. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52046. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52047. // tube geometry
  52048. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52049. var tangents = path3D.getTangents();
  52050. var normals = path3D.getNormals();
  52051. var distances = path3D.getDistances();
  52052. var pi2 = Math.PI * 2;
  52053. var step = pi2 / tessellation * arc;
  52054. var returnRadius = function () { return radius; };
  52055. var radiusFunctionFinal = radiusFunction || returnRadius;
  52056. var circlePath;
  52057. var rad;
  52058. var normal;
  52059. var rotated;
  52060. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52061. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52062. for (var i = 0; i < path.length; i++) {
  52063. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52064. circlePath = Array(); // current circle array
  52065. normal = normals[i]; // current normal
  52066. for (var t = 0; t < tessellation; t++) {
  52067. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52068. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52069. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52070. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52071. circlePath[t] = rotated;
  52072. }
  52073. circlePaths[index] = circlePath;
  52074. index++;
  52075. }
  52076. // cap
  52077. var capPath = function (nbPoints, pathIndex) {
  52078. var pointCap = Array();
  52079. for (var i = 0; i < nbPoints; i++) {
  52080. pointCap.push(path[pathIndex]);
  52081. }
  52082. return pointCap;
  52083. };
  52084. switch (cap) {
  52085. case BABYLON.Mesh.NO_CAP:
  52086. break;
  52087. case BABYLON.Mesh.CAP_START:
  52088. circlePaths[0] = capPath(tessellation, 0);
  52089. circlePaths[1] = circlePaths[2].slice(0);
  52090. break;
  52091. case BABYLON.Mesh.CAP_END:
  52092. circlePaths[index] = circlePaths[index - 1].slice(0);
  52093. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52094. break;
  52095. case BABYLON.Mesh.CAP_ALL:
  52096. circlePaths[0] = capPath(tessellation, 0);
  52097. circlePaths[1] = circlePaths[2].slice(0);
  52098. circlePaths[index] = circlePaths[index - 1].slice(0);
  52099. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52100. break;
  52101. default:
  52102. break;
  52103. }
  52104. return circlePaths;
  52105. };
  52106. var path3D;
  52107. var pathArray;
  52108. if (instance) {
  52109. var arc = options.arc || instance.arc;
  52110. path3D = (instance.path3D).update(path);
  52111. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52112. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52113. instance.path3D = path3D;
  52114. instance.pathArray = pathArray;
  52115. instance.arc = arc;
  52116. instance.radius = radius;
  52117. return instance;
  52118. }
  52119. // tube creation
  52120. path3D = new BABYLON.Path3D(path);
  52121. var newPathArray = new Array();
  52122. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52123. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52124. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52125. tube.pathArray = pathArray;
  52126. tube.path3D = path3D;
  52127. tube.tessellation = tessellation;
  52128. tube.cap = cap;
  52129. tube.arc = options.arc;
  52130. tube.radius = radius;
  52131. return tube;
  52132. };
  52133. /**
  52134. * Creates a polyhedron mesh.
  52135. *
  52136. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  52137. * 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
  52138. * to choose the wanted type.
  52139. * The parameter `size` (positive float, default 1) sets the polygon size.
  52140. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  52141. * 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`.
  52142. * 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
  52143. * 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)`).
  52144. * 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
  52145. * 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.
  52146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52147. * 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).
  52148. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52150. */
  52151. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  52152. var polyhedron = new BABYLON.Mesh(name, scene);
  52153. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52154. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  52155. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  52156. vertexData.applyToMesh(polyhedron, options.updatable);
  52157. return polyhedron;
  52158. };
  52159. /**
  52160. * Creates a decal mesh.
  52161. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  52162. * 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.
  52163. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  52164. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  52165. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  52166. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  52167. */
  52168. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  52169. var indices = sourceMesh.getIndices();
  52170. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52171. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52172. var position = options.position || BABYLON.Vector3.Zero();
  52173. var normal = options.normal || BABYLON.Vector3.Up();
  52174. var size = options.size || BABYLON.Vector3.One();
  52175. var angle = options.angle || 0;
  52176. // Getting correct rotation
  52177. if (!normal) {
  52178. var target = new BABYLON.Vector3(0, 0, 1);
  52179. var camera = sourceMesh.getScene().activeCamera;
  52180. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  52181. normal = camera.globalPosition.subtract(cameraWorldTarget);
  52182. }
  52183. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  52184. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  52185. var pitch = Math.atan2(normal.y, len);
  52186. // Matrix
  52187. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  52188. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  52189. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  52190. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  52191. var vertexData = new BABYLON.VertexData();
  52192. vertexData.indices = [];
  52193. vertexData.positions = [];
  52194. vertexData.normals = [];
  52195. vertexData.uvs = [];
  52196. var currentVertexDataIndex = 0;
  52197. var extractDecalVector3 = function (indexId) {
  52198. var result = new BABYLON.PositionNormalVertex();
  52199. if (!indices || !positions || !normals) {
  52200. return result;
  52201. }
  52202. var vertexId = indices[indexId];
  52203. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  52204. // Send vector to decal local world
  52205. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  52206. // Get normal
  52207. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  52208. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  52209. return result;
  52210. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  52211. var clip = function (vertices, axis) {
  52212. if (vertices.length === 0) {
  52213. return vertices;
  52214. }
  52215. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  52216. var clipVertices = function (v0, v1) {
  52217. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  52218. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  52219. };
  52220. var result = new Array();
  52221. for (var index = 0; index < vertices.length; index += 3) {
  52222. var v1Out;
  52223. var v2Out;
  52224. var v3Out;
  52225. var total = 0;
  52226. var nV1 = null;
  52227. var nV2 = null;
  52228. var nV3 = null;
  52229. var nV4 = null;
  52230. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  52231. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  52232. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  52233. v1Out = d1 > 0;
  52234. v2Out = d2 > 0;
  52235. v3Out = d3 > 0;
  52236. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  52237. switch (total) {
  52238. case 0:
  52239. result.push(vertices[index]);
  52240. result.push(vertices[index + 1]);
  52241. result.push(vertices[index + 2]);
  52242. break;
  52243. case 1:
  52244. if (v1Out) {
  52245. nV1 = vertices[index + 1];
  52246. nV2 = vertices[index + 2];
  52247. nV3 = clipVertices(vertices[index], nV1);
  52248. nV4 = clipVertices(vertices[index], nV2);
  52249. }
  52250. if (v2Out) {
  52251. nV1 = vertices[index];
  52252. nV2 = vertices[index + 2];
  52253. nV3 = clipVertices(vertices[index + 1], nV1);
  52254. nV4 = clipVertices(vertices[index + 1], nV2);
  52255. result.push(nV3);
  52256. result.push(nV2.clone());
  52257. result.push(nV1.clone());
  52258. result.push(nV2.clone());
  52259. result.push(nV3.clone());
  52260. result.push(nV4);
  52261. break;
  52262. }
  52263. if (v3Out) {
  52264. nV1 = vertices[index];
  52265. nV2 = vertices[index + 1];
  52266. nV3 = clipVertices(vertices[index + 2], nV1);
  52267. nV4 = clipVertices(vertices[index + 2], nV2);
  52268. }
  52269. if (nV1 && nV2 && nV3 && nV4) {
  52270. result.push(nV1.clone());
  52271. result.push(nV2.clone());
  52272. result.push(nV3);
  52273. result.push(nV4);
  52274. result.push(nV3.clone());
  52275. result.push(nV2.clone());
  52276. }
  52277. break;
  52278. case 2:
  52279. if (!v1Out) {
  52280. nV1 = vertices[index].clone();
  52281. nV2 = clipVertices(nV1, vertices[index + 1]);
  52282. nV3 = clipVertices(nV1, vertices[index + 2]);
  52283. result.push(nV1);
  52284. result.push(nV2);
  52285. result.push(nV3);
  52286. }
  52287. if (!v2Out) {
  52288. nV1 = vertices[index + 1].clone();
  52289. nV2 = clipVertices(nV1, vertices[index + 2]);
  52290. nV3 = clipVertices(nV1, vertices[index]);
  52291. result.push(nV1);
  52292. result.push(nV2);
  52293. result.push(nV3);
  52294. }
  52295. if (!v3Out) {
  52296. nV1 = vertices[index + 2].clone();
  52297. nV2 = clipVertices(nV1, vertices[index]);
  52298. nV3 = clipVertices(nV1, vertices[index + 1]);
  52299. result.push(nV1);
  52300. result.push(nV2);
  52301. result.push(nV3);
  52302. }
  52303. break;
  52304. case 3:
  52305. break;
  52306. }
  52307. }
  52308. return result;
  52309. };
  52310. for (var index = 0; index < indices.length; index += 3) {
  52311. var faceVertices = new Array();
  52312. faceVertices.push(extractDecalVector3(index));
  52313. faceVertices.push(extractDecalVector3(index + 1));
  52314. faceVertices.push(extractDecalVector3(index + 2));
  52315. // Clip
  52316. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52317. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52318. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52319. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52320. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52321. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52322. if (faceVertices.length === 0) {
  52323. continue;
  52324. }
  52325. // Add UVs and get back to world
  52326. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  52327. var vertex = faceVertices[vIndex];
  52328. //TODO check for Int32Array | Uint32Array | Uint16Array
  52329. vertexData.indices.push(currentVertexDataIndex);
  52330. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  52331. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  52332. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  52333. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  52334. currentVertexDataIndex++;
  52335. }
  52336. }
  52337. // Return mesh
  52338. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  52339. vertexData.applyToMesh(decal);
  52340. decal.position = position.clone();
  52341. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  52342. return decal;
  52343. };
  52344. // Privates
  52345. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  52346. // extrusion geometry
  52347. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  52348. var tangents = path3D.getTangents();
  52349. var normals = path3D.getNormals();
  52350. var binormals = path3D.getBinormals();
  52351. var distances = path3D.getDistances();
  52352. var angle = 0;
  52353. var returnScale = function () { return scale !== null ? scale : 1; };
  52354. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  52355. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  52356. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  52357. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52358. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52359. for (var i = 0; i < curve.length; i++) {
  52360. var shapePath = new Array();
  52361. var angleStep = rotate(i, distances[i]);
  52362. var scaleRatio = scl(i, distances[i]);
  52363. for (var p = 0; p < shape.length; p++) {
  52364. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  52365. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  52366. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  52367. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  52368. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  52369. shapePath[p] = rotated;
  52370. }
  52371. shapePaths[index] = shapePath;
  52372. angle += angleStep;
  52373. index++;
  52374. }
  52375. // cap
  52376. var capPath = function (shapePath) {
  52377. var pointCap = Array();
  52378. var barycenter = BABYLON.Vector3.Zero();
  52379. var i;
  52380. for (i = 0; i < shapePath.length; i++) {
  52381. barycenter.addInPlace(shapePath[i]);
  52382. }
  52383. barycenter.scaleInPlace(1.0 / shapePath.length);
  52384. for (i = 0; i < shapePath.length; i++) {
  52385. pointCap.push(barycenter);
  52386. }
  52387. return pointCap;
  52388. };
  52389. switch (cap) {
  52390. case BABYLON.Mesh.NO_CAP:
  52391. break;
  52392. case BABYLON.Mesh.CAP_START:
  52393. shapePaths[0] = capPath(shapePaths[2]);
  52394. shapePaths[1] = shapePaths[2];
  52395. break;
  52396. case BABYLON.Mesh.CAP_END:
  52397. shapePaths[index] = shapePaths[index - 1];
  52398. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52399. break;
  52400. case BABYLON.Mesh.CAP_ALL:
  52401. shapePaths[0] = capPath(shapePaths[2]);
  52402. shapePaths[1] = shapePaths[2];
  52403. shapePaths[index] = shapePaths[index - 1];
  52404. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52405. break;
  52406. default:
  52407. break;
  52408. }
  52409. return shapePaths;
  52410. };
  52411. var path3D;
  52412. var pathArray;
  52413. if (instance) {
  52414. path3D = (instance.path3D).update(curve);
  52415. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  52416. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  52417. return instance;
  52418. }
  52419. // extruded shape creation
  52420. path3D = new BABYLON.Path3D(curve);
  52421. var newShapePaths = new Array();
  52422. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52423. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  52424. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  52425. extrudedGeneric.pathArray = pathArray;
  52426. extrudedGeneric.path3D = path3D;
  52427. extrudedGeneric.cap = cap;
  52428. return extrudedGeneric;
  52429. };
  52430. return MeshBuilder;
  52431. }());
  52432. BABYLON.MeshBuilder = MeshBuilder;
  52433. })(BABYLON || (BABYLON = {}));
  52434. //# sourceMappingURL=babylon.meshBuilder.js.map
  52435. var BABYLON;
  52436. (function (BABYLON) {
  52437. var AudioEngine = /** @class */ (function () {
  52438. function AudioEngine() {
  52439. this._audioContext = null;
  52440. this._audioContextInitialized = false;
  52441. this.canUseWebAudio = false;
  52442. this.WarnedWebAudioUnsupported = false;
  52443. this.unlocked = false;
  52444. this.isMP3supported = false;
  52445. this.isOGGsupported = false;
  52446. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52447. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52448. this.canUseWebAudio = true;
  52449. }
  52450. var audioElem = document.createElement('audio');
  52451. try {
  52452. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52453. this.isMP3supported = true;
  52454. }
  52455. }
  52456. catch (e) {
  52457. // protect error during capability check.
  52458. }
  52459. try {
  52460. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52461. this.isOGGsupported = true;
  52462. }
  52463. }
  52464. catch (e) {
  52465. // protect error during capability check.
  52466. }
  52467. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52468. this._unlockiOSaudio();
  52469. }
  52470. else {
  52471. this.unlocked = true;
  52472. }
  52473. }
  52474. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52475. get: function () {
  52476. if (!this._audioContextInitialized) {
  52477. this._initializeAudioContext();
  52478. }
  52479. return this._audioContext;
  52480. },
  52481. enumerable: true,
  52482. configurable: true
  52483. });
  52484. AudioEngine.prototype._unlockiOSaudio = function () {
  52485. var _this = this;
  52486. var unlockaudio = function () {
  52487. if (!_this.audioContext) {
  52488. return;
  52489. }
  52490. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52491. var source = _this.audioContext.createBufferSource();
  52492. source.buffer = buffer;
  52493. source.connect(_this.audioContext.destination);
  52494. source.start(0);
  52495. setTimeout(function () {
  52496. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52497. _this.unlocked = true;
  52498. window.removeEventListener('touchend', unlockaudio, false);
  52499. if (_this.onAudioUnlocked) {
  52500. _this.onAudioUnlocked();
  52501. }
  52502. }
  52503. }, 0);
  52504. };
  52505. window.addEventListener('touchend', unlockaudio, false);
  52506. };
  52507. AudioEngine.prototype._initializeAudioContext = function () {
  52508. try {
  52509. if (this.canUseWebAudio) {
  52510. this._audioContext = new AudioContext();
  52511. // create a global volume gain node
  52512. this.masterGain = this._audioContext.createGain();
  52513. this.masterGain.gain.value = 1;
  52514. this.masterGain.connect(this._audioContext.destination);
  52515. this._audioContextInitialized = true;
  52516. }
  52517. }
  52518. catch (e) {
  52519. this.canUseWebAudio = false;
  52520. BABYLON.Tools.Error("Web Audio: " + e.message);
  52521. }
  52522. };
  52523. AudioEngine.prototype.dispose = function () {
  52524. if (this.canUseWebAudio && this._audioContextInitialized) {
  52525. if (this._connectedAnalyser && this._audioContext) {
  52526. this._connectedAnalyser.stopDebugCanvas();
  52527. this._connectedAnalyser.dispose();
  52528. this.masterGain.disconnect();
  52529. this.masterGain.connect(this._audioContext.destination);
  52530. this._connectedAnalyser = null;
  52531. }
  52532. this.masterGain.gain.value = 1;
  52533. }
  52534. this.WarnedWebAudioUnsupported = false;
  52535. };
  52536. AudioEngine.prototype.getGlobalVolume = function () {
  52537. if (this.canUseWebAudio && this._audioContextInitialized) {
  52538. return this.masterGain.gain.value;
  52539. }
  52540. else {
  52541. return -1;
  52542. }
  52543. };
  52544. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52545. if (this.canUseWebAudio && this._audioContextInitialized) {
  52546. this.masterGain.gain.value = newVolume;
  52547. }
  52548. };
  52549. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52550. if (this._connectedAnalyser) {
  52551. this._connectedAnalyser.stopDebugCanvas();
  52552. }
  52553. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52554. this._connectedAnalyser = analyser;
  52555. this.masterGain.disconnect();
  52556. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52557. }
  52558. };
  52559. return AudioEngine;
  52560. }());
  52561. BABYLON.AudioEngine = AudioEngine;
  52562. })(BABYLON || (BABYLON = {}));
  52563. //# sourceMappingURL=babylon.audioEngine.js.map
  52564. var BABYLON;
  52565. (function (BABYLON) {
  52566. var Sound = /** @class */ (function () {
  52567. /**
  52568. * Create a sound and attach it to a scene
  52569. * @param name Name of your sound
  52570. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52571. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52572. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52573. */
  52574. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52575. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52576. var _this = this;
  52577. this.autoplay = false;
  52578. this.loop = false;
  52579. this.useCustomAttenuation = false;
  52580. this.spatialSound = false;
  52581. this.refDistance = 1;
  52582. this.rolloffFactor = 1;
  52583. this.maxDistance = 100;
  52584. this.distanceModel = "linear";
  52585. this._panningModel = "equalpower";
  52586. this._playbackRate = 1;
  52587. this._streaming = false;
  52588. this._startTime = 0;
  52589. this._startOffset = 0;
  52590. this._position = BABYLON.Vector3.Zero();
  52591. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52592. this._volume = 1;
  52593. this._isReadyToPlay = false;
  52594. this.isPlaying = false;
  52595. this.isPaused = false;
  52596. this._isDirectional = false;
  52597. // Used if you'd like to create a directional sound.
  52598. // If not set, the sound will be omnidirectional
  52599. this._coneInnerAngle = 360;
  52600. this._coneOuterAngle = 360;
  52601. this._coneOuterGain = 0;
  52602. this._isOutputConnected = false;
  52603. this._urlType = "Unknown";
  52604. this.name = name;
  52605. this._scene = scene;
  52606. this._readyToPlayCallback = readyToPlayCallback;
  52607. // Default custom attenuation function is a linear attenuation
  52608. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52609. if (currentDistance < maxDistance) {
  52610. return currentVolume * (1 - currentDistance / maxDistance);
  52611. }
  52612. else {
  52613. return 0;
  52614. }
  52615. };
  52616. if (options) {
  52617. this.autoplay = options.autoplay || false;
  52618. this.loop = options.loop || false;
  52619. // if volume === 0, we need another way to check this option
  52620. if (options.volume !== undefined) {
  52621. this._volume = options.volume;
  52622. }
  52623. this.spatialSound = options.spatialSound || false;
  52624. this.maxDistance = options.maxDistance || 100;
  52625. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52626. this.rolloffFactor = options.rolloffFactor || 1;
  52627. this.refDistance = options.refDistance || 1;
  52628. this.distanceModel = options.distanceModel || "linear";
  52629. this._playbackRate = options.playbackRate || 1;
  52630. this._streaming = options.streaming || false;
  52631. }
  52632. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52633. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52634. this._soundGain.gain.value = this._volume;
  52635. this._inputAudioNode = this._soundGain;
  52636. this._ouputAudioNode = this._soundGain;
  52637. if (this.spatialSound) {
  52638. this._createSpatialParameters();
  52639. }
  52640. this._scene.mainSoundTrack.AddSound(this);
  52641. var validParameter = true;
  52642. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52643. if (urlOrArrayBuffer) {
  52644. if (typeof (urlOrArrayBuffer) === "string")
  52645. this._urlType = "String";
  52646. if (Array.isArray(urlOrArrayBuffer))
  52647. this._urlType = "Array";
  52648. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52649. this._urlType = "ArrayBuffer";
  52650. var urls = [];
  52651. var codecSupportedFound = false;
  52652. switch (this._urlType) {
  52653. case "ArrayBuffer":
  52654. if (urlOrArrayBuffer.byteLength > 0) {
  52655. codecSupportedFound = true;
  52656. this._soundLoaded(urlOrArrayBuffer);
  52657. }
  52658. break;
  52659. case "String":
  52660. urls.push(urlOrArrayBuffer);
  52661. case "Array":
  52662. if (urls.length === 0)
  52663. urls = urlOrArrayBuffer;
  52664. // If we found a supported format, we load it immediately and stop the loop
  52665. for (var i = 0; i < urls.length; i++) {
  52666. var url = urls[i];
  52667. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  52668. codecSupportedFound = true;
  52669. }
  52670. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  52671. codecSupportedFound = true;
  52672. }
  52673. if (url.indexOf(".wav", url.length - 4) !== -1) {
  52674. codecSupportedFound = true;
  52675. }
  52676. if (url.indexOf("blob:") !== -1) {
  52677. codecSupportedFound = true;
  52678. }
  52679. if (codecSupportedFound) {
  52680. // Loading sound using XHR2
  52681. if (!this._streaming) {
  52682. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  52683. }
  52684. else {
  52685. this._htmlAudioElement = new Audio(url);
  52686. this._htmlAudioElement.controls = false;
  52687. this._htmlAudioElement.loop = this.loop;
  52688. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  52689. this._htmlAudioElement.preload = "auto";
  52690. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  52691. _this._isReadyToPlay = true;
  52692. if (_this.autoplay) {
  52693. _this.play();
  52694. }
  52695. if (_this._readyToPlayCallback) {
  52696. _this._readyToPlayCallback();
  52697. }
  52698. });
  52699. document.body.appendChild(this._htmlAudioElement);
  52700. }
  52701. break;
  52702. }
  52703. }
  52704. break;
  52705. default:
  52706. validParameter = false;
  52707. break;
  52708. }
  52709. if (!validParameter) {
  52710. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  52711. }
  52712. else {
  52713. if (!codecSupportedFound) {
  52714. this._isReadyToPlay = true;
  52715. // Simulating a ready to play event to avoid breaking code path
  52716. if (this._readyToPlayCallback) {
  52717. window.setTimeout(function () {
  52718. if (_this._readyToPlayCallback) {
  52719. _this._readyToPlayCallback();
  52720. }
  52721. }, 1000);
  52722. }
  52723. }
  52724. }
  52725. }
  52726. }
  52727. else {
  52728. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  52729. this._scene.mainSoundTrack.AddSound(this);
  52730. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  52731. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  52732. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  52733. }
  52734. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  52735. if (this._readyToPlayCallback) {
  52736. window.setTimeout(function () {
  52737. if (_this._readyToPlayCallback) {
  52738. _this._readyToPlayCallback();
  52739. }
  52740. }, 1000);
  52741. }
  52742. }
  52743. }
  52744. Sound.prototype.dispose = function () {
  52745. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  52746. if (this.isPlaying) {
  52747. this.stop();
  52748. }
  52749. this._isReadyToPlay = false;
  52750. if (this.soundTrackId === -1) {
  52751. this._scene.mainSoundTrack.RemoveSound(this);
  52752. }
  52753. else {
  52754. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  52755. }
  52756. if (this._soundGain) {
  52757. this._soundGain.disconnect();
  52758. this._soundGain = null;
  52759. }
  52760. if (this._soundPanner) {
  52761. this._soundPanner.disconnect();
  52762. this._soundPanner = null;
  52763. }
  52764. if (this._soundSource) {
  52765. this._soundSource.disconnect();
  52766. this._soundSource = null;
  52767. }
  52768. this._audioBuffer = null;
  52769. if (this._htmlAudioElement) {
  52770. this._htmlAudioElement.pause();
  52771. this._htmlAudioElement.src = "";
  52772. document.body.removeChild(this._htmlAudioElement);
  52773. }
  52774. if (this._connectedMesh && this._registerFunc) {
  52775. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52776. this._connectedMesh = null;
  52777. }
  52778. }
  52779. };
  52780. Sound.prototype.isReady = function () {
  52781. return this._isReadyToPlay;
  52782. };
  52783. Sound.prototype._soundLoaded = function (audioData) {
  52784. var _this = this;
  52785. if (!BABYLON.Engine.audioEngine.audioContext) {
  52786. return;
  52787. }
  52788. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  52789. _this._audioBuffer = buffer;
  52790. _this._isReadyToPlay = true;
  52791. if (_this.autoplay) {
  52792. _this.play();
  52793. }
  52794. if (_this._readyToPlayCallback) {
  52795. _this._readyToPlayCallback();
  52796. }
  52797. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  52798. };
  52799. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  52800. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52801. this._audioBuffer = audioBuffer;
  52802. this._isReadyToPlay = true;
  52803. }
  52804. };
  52805. Sound.prototype.updateOptions = function (options) {
  52806. if (options) {
  52807. this.loop = options.loop || this.loop;
  52808. this.maxDistance = options.maxDistance || this.maxDistance;
  52809. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  52810. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  52811. this.refDistance = options.refDistance || this.refDistance;
  52812. this.distanceModel = options.distanceModel || this.distanceModel;
  52813. this._playbackRate = options.playbackRate || this._playbackRate;
  52814. this._updateSpatialParameters();
  52815. if (this.isPlaying) {
  52816. if (this._streaming) {
  52817. this._htmlAudioElement.playbackRate = this._playbackRate;
  52818. }
  52819. else {
  52820. if (this._soundSource) {
  52821. this._soundSource.playbackRate.value = this._playbackRate;
  52822. }
  52823. }
  52824. }
  52825. }
  52826. };
  52827. Sound.prototype._createSpatialParameters = function () {
  52828. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52829. if (this._scene.headphone) {
  52830. this._panningModel = "HRTF";
  52831. }
  52832. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  52833. this._updateSpatialParameters();
  52834. this._soundPanner.connect(this._ouputAudioNode);
  52835. this._inputAudioNode = this._soundPanner;
  52836. }
  52837. };
  52838. Sound.prototype._updateSpatialParameters = function () {
  52839. if (this.spatialSound && this._soundPanner) {
  52840. if (this.useCustomAttenuation) {
  52841. // Tricks to disable in a way embedded Web Audio attenuation
  52842. this._soundPanner.distanceModel = "linear";
  52843. this._soundPanner.maxDistance = Number.MAX_VALUE;
  52844. this._soundPanner.refDistance = 1;
  52845. this._soundPanner.rolloffFactor = 1;
  52846. this._soundPanner.panningModel = this._panningModel;
  52847. }
  52848. else {
  52849. this._soundPanner.distanceModel = this.distanceModel;
  52850. this._soundPanner.maxDistance = this.maxDistance;
  52851. this._soundPanner.refDistance = this.refDistance;
  52852. this._soundPanner.rolloffFactor = this.rolloffFactor;
  52853. this._soundPanner.panningModel = this._panningModel;
  52854. }
  52855. }
  52856. };
  52857. Sound.prototype.switchPanningModelToHRTF = function () {
  52858. this._panningModel = "HRTF";
  52859. this._switchPanningModel();
  52860. };
  52861. Sound.prototype.switchPanningModelToEqualPower = function () {
  52862. this._panningModel = "equalpower";
  52863. this._switchPanningModel();
  52864. };
  52865. Sound.prototype._switchPanningModel = function () {
  52866. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52867. this._soundPanner.panningModel = this._panningModel;
  52868. }
  52869. };
  52870. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  52871. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52872. if (this._isOutputConnected) {
  52873. this._ouputAudioNode.disconnect();
  52874. }
  52875. this._ouputAudioNode.connect(soundTrackAudioNode);
  52876. this._isOutputConnected = true;
  52877. }
  52878. };
  52879. /**
  52880. * Transform this sound into a directional source
  52881. * @param coneInnerAngle Size of the inner cone in degree
  52882. * @param coneOuterAngle Size of the outer cone in degree
  52883. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  52884. */
  52885. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  52886. if (coneOuterAngle < coneInnerAngle) {
  52887. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  52888. return;
  52889. }
  52890. this._coneInnerAngle = coneInnerAngle;
  52891. this._coneOuterAngle = coneOuterAngle;
  52892. this._coneOuterGain = coneOuterGain;
  52893. this._isDirectional = true;
  52894. if (this.isPlaying && this.loop) {
  52895. this.stop();
  52896. this.play();
  52897. }
  52898. };
  52899. Sound.prototype.setPosition = function (newPosition) {
  52900. this._position = newPosition;
  52901. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52902. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52903. }
  52904. };
  52905. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  52906. this._localDirection = newLocalDirection;
  52907. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  52908. this._updateDirection();
  52909. }
  52910. };
  52911. Sound.prototype._updateDirection = function () {
  52912. if (!this._connectedMesh || !this._soundPanner) {
  52913. return;
  52914. }
  52915. var mat = this._connectedMesh.getWorldMatrix();
  52916. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  52917. direction.normalize();
  52918. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  52919. };
  52920. Sound.prototype.updateDistanceFromListener = function () {
  52921. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  52922. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  52923. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  52924. }
  52925. };
  52926. Sound.prototype.setAttenuationFunction = function (callback) {
  52927. this._customAttenuationFunction = callback;
  52928. };
  52929. /**
  52930. * Play the sound
  52931. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  52932. * @param offset (optional) Start the sound setting it at a specific time
  52933. */
  52934. Sound.prototype.play = function (time, offset) {
  52935. var _this = this;
  52936. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  52937. try {
  52938. if (this._startOffset < 0) {
  52939. time = -this._startOffset;
  52940. this._startOffset = 0;
  52941. }
  52942. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  52943. if (!this._soundSource || !this._streamingSource) {
  52944. if (this.spatialSound && this._soundPanner) {
  52945. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  52946. if (this._isDirectional) {
  52947. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  52948. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  52949. this._soundPanner.coneOuterGain = this._coneOuterGain;
  52950. if (this._connectedMesh) {
  52951. this._updateDirection();
  52952. }
  52953. else {
  52954. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  52955. }
  52956. }
  52957. }
  52958. }
  52959. if (this._streaming) {
  52960. if (!this._streamingSource) {
  52961. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  52962. this._htmlAudioElement.onended = function () { _this._onended(); };
  52963. this._htmlAudioElement.playbackRate = this._playbackRate;
  52964. }
  52965. this._streamingSource.disconnect();
  52966. this._streamingSource.connect(this._inputAudioNode);
  52967. this._htmlAudioElement.play();
  52968. }
  52969. else {
  52970. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  52971. this._soundSource.buffer = this._audioBuffer;
  52972. this._soundSource.connect(this._inputAudioNode);
  52973. this._soundSource.loop = this.loop;
  52974. this._soundSource.playbackRate.value = this._playbackRate;
  52975. this._soundSource.onended = function () { _this._onended(); };
  52976. if (this._soundSource.buffer) {
  52977. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  52978. }
  52979. }
  52980. this._startTime = startTime;
  52981. this.isPlaying = true;
  52982. this.isPaused = false;
  52983. }
  52984. catch (ex) {
  52985. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  52986. }
  52987. }
  52988. };
  52989. Sound.prototype._onended = function () {
  52990. this.isPlaying = false;
  52991. if (this.onended) {
  52992. this.onended();
  52993. }
  52994. };
  52995. /**
  52996. * Stop the sound
  52997. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  52998. */
  52999. Sound.prototype.stop = function (time) {
  53000. if (this.isPlaying) {
  53001. if (this._streaming) {
  53002. this._htmlAudioElement.pause();
  53003. // Test needed for Firefox or it will generate an Invalid State Error
  53004. if (this._htmlAudioElement.currentTime > 0) {
  53005. this._htmlAudioElement.currentTime = 0;
  53006. }
  53007. }
  53008. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53009. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53010. this._soundSource.stop(stopTime);
  53011. this._soundSource.onended = function () { };
  53012. if (!this.isPaused) {
  53013. this._startOffset = 0;
  53014. }
  53015. }
  53016. this.isPlaying = false;
  53017. }
  53018. };
  53019. Sound.prototype.pause = function () {
  53020. if (this.isPlaying) {
  53021. this.isPaused = true;
  53022. if (this._streaming) {
  53023. this._htmlAudioElement.pause();
  53024. }
  53025. else if (BABYLON.Engine.audioEngine.audioContext) {
  53026. this.stop(0);
  53027. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53028. }
  53029. }
  53030. };
  53031. Sound.prototype.setVolume = function (newVolume, time) {
  53032. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53033. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53034. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53035. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53036. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53037. }
  53038. else {
  53039. this._soundGain.gain.value = newVolume;
  53040. }
  53041. }
  53042. this._volume = newVolume;
  53043. };
  53044. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53045. this._playbackRate = newPlaybackRate;
  53046. if (this.isPlaying) {
  53047. if (this._streaming) {
  53048. this._htmlAudioElement.playbackRate = this._playbackRate;
  53049. }
  53050. else if (this._soundSource) {
  53051. this._soundSource.playbackRate.value = this._playbackRate;
  53052. }
  53053. }
  53054. };
  53055. Sound.prototype.getVolume = function () {
  53056. return this._volume;
  53057. };
  53058. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53059. var _this = this;
  53060. if (this._connectedMesh && this._registerFunc) {
  53061. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53062. this._registerFunc = null;
  53063. }
  53064. this._connectedMesh = meshToConnectTo;
  53065. if (!this.spatialSound) {
  53066. this.spatialSound = true;
  53067. this._createSpatialParameters();
  53068. if (this.isPlaying && this.loop) {
  53069. this.stop();
  53070. this.play();
  53071. }
  53072. }
  53073. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53074. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53075. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53076. };
  53077. Sound.prototype.detachFromMesh = function () {
  53078. if (this._connectedMesh && this._registerFunc) {
  53079. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53080. this._registerFunc = null;
  53081. this._connectedMesh = null;
  53082. }
  53083. };
  53084. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53085. if (!node.getBoundingInfo) {
  53086. return;
  53087. }
  53088. var mesh = node;
  53089. var boundingInfo = mesh.getBoundingInfo();
  53090. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53091. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53092. this._updateDirection();
  53093. }
  53094. };
  53095. Sound.prototype.clone = function () {
  53096. var _this = this;
  53097. if (!this._streaming) {
  53098. var setBufferAndRun = function () {
  53099. if (_this._isReadyToPlay) {
  53100. clonedSound._audioBuffer = _this.getAudioBuffer();
  53101. clonedSound._isReadyToPlay = true;
  53102. if (clonedSound.autoplay) {
  53103. clonedSound.play();
  53104. }
  53105. }
  53106. else {
  53107. window.setTimeout(setBufferAndRun, 300);
  53108. }
  53109. };
  53110. var currentOptions = {
  53111. autoplay: this.autoplay, loop: this.loop,
  53112. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53113. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53114. refDistance: this.refDistance, distanceModel: this.distanceModel
  53115. };
  53116. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53117. if (this.useCustomAttenuation) {
  53118. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53119. }
  53120. clonedSound.setPosition(this._position);
  53121. clonedSound.setPlaybackRate(this._playbackRate);
  53122. setBufferAndRun();
  53123. return clonedSound;
  53124. }
  53125. else {
  53126. return null;
  53127. }
  53128. };
  53129. Sound.prototype.getAudioBuffer = function () {
  53130. return this._audioBuffer;
  53131. };
  53132. Sound.prototype.serialize = function () {
  53133. var serializationObject = {
  53134. name: this.name,
  53135. url: this.name,
  53136. autoplay: this.autoplay,
  53137. loop: this.loop,
  53138. volume: this._volume,
  53139. spatialSound: this.spatialSound,
  53140. maxDistance: this.maxDistance,
  53141. rolloffFactor: this.rolloffFactor,
  53142. refDistance: this.refDistance,
  53143. distanceModel: this.distanceModel,
  53144. playbackRate: this._playbackRate,
  53145. panningModel: this._panningModel,
  53146. soundTrackId: this.soundTrackId
  53147. };
  53148. if (this.spatialSound) {
  53149. if (this._connectedMesh)
  53150. serializationObject.connectedMeshId = this._connectedMesh.id;
  53151. serializationObject.position = this._position.asArray();
  53152. serializationObject.refDistance = this.refDistance;
  53153. serializationObject.distanceModel = this.distanceModel;
  53154. serializationObject.isDirectional = this._isDirectional;
  53155. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  53156. serializationObject.coneInnerAngle = this._coneInnerAngle;
  53157. serializationObject.coneOuterAngle = this._coneOuterAngle;
  53158. serializationObject.coneOuterGain = this._coneOuterGain;
  53159. }
  53160. return serializationObject;
  53161. };
  53162. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  53163. var soundName = parsedSound.name;
  53164. var soundUrl;
  53165. if (parsedSound.url) {
  53166. soundUrl = rootUrl + parsedSound.url;
  53167. }
  53168. else {
  53169. soundUrl = rootUrl + soundName;
  53170. }
  53171. var options = {
  53172. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  53173. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  53174. rolloffFactor: parsedSound.rolloffFactor,
  53175. refDistance: parsedSound.refDistance,
  53176. distanceModel: parsedSound.distanceModel,
  53177. playbackRate: parsedSound.playbackRate
  53178. };
  53179. var newSound;
  53180. if (!sourceSound) {
  53181. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  53182. scene._addPendingData(newSound);
  53183. }
  53184. else {
  53185. var setBufferAndRun = function () {
  53186. if (sourceSound._isReadyToPlay) {
  53187. newSound._audioBuffer = sourceSound.getAudioBuffer();
  53188. newSound._isReadyToPlay = true;
  53189. if (newSound.autoplay) {
  53190. newSound.play();
  53191. }
  53192. }
  53193. else {
  53194. window.setTimeout(setBufferAndRun, 300);
  53195. }
  53196. };
  53197. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  53198. setBufferAndRun();
  53199. }
  53200. if (parsedSound.position) {
  53201. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  53202. newSound.setPosition(soundPosition);
  53203. }
  53204. if (parsedSound.isDirectional) {
  53205. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  53206. if (parsedSound.localDirectionToMesh) {
  53207. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  53208. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  53209. }
  53210. }
  53211. if (parsedSound.connectedMeshId) {
  53212. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  53213. if (connectedMesh) {
  53214. newSound.attachToMesh(connectedMesh);
  53215. }
  53216. }
  53217. return newSound;
  53218. };
  53219. return Sound;
  53220. }());
  53221. BABYLON.Sound = Sound;
  53222. })(BABYLON || (BABYLON = {}));
  53223. //# sourceMappingURL=babylon.sound.js.map
  53224. var BABYLON;
  53225. (function (BABYLON) {
  53226. var SoundTrack = /** @class */ (function () {
  53227. function SoundTrack(scene, options) {
  53228. this.id = -1;
  53229. this._isMainTrack = false;
  53230. this._isInitialized = false;
  53231. this._scene = scene;
  53232. this.soundCollection = new Array();
  53233. this._options = options;
  53234. if (!this._isMainTrack) {
  53235. this._scene.soundTracks.push(this);
  53236. this.id = this._scene.soundTracks.length - 1;
  53237. }
  53238. }
  53239. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  53240. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53241. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  53242. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  53243. if (this._options) {
  53244. if (this._options.volume) {
  53245. this._outputAudioNode.gain.value = this._options.volume;
  53246. }
  53247. if (this._options.mainTrack) {
  53248. this._isMainTrack = this._options.mainTrack;
  53249. }
  53250. }
  53251. this._isInitialized = true;
  53252. }
  53253. };
  53254. SoundTrack.prototype.dispose = function () {
  53255. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53256. if (this._connectedAnalyser) {
  53257. this._connectedAnalyser.stopDebugCanvas();
  53258. }
  53259. while (this.soundCollection.length) {
  53260. this.soundCollection[0].dispose();
  53261. }
  53262. if (this._outputAudioNode) {
  53263. this._outputAudioNode.disconnect();
  53264. }
  53265. this._outputAudioNode = null;
  53266. }
  53267. };
  53268. SoundTrack.prototype.AddSound = function (sound) {
  53269. if (!this._isInitialized) {
  53270. this._initializeSoundTrackAudioGraph();
  53271. }
  53272. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53273. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53274. }
  53275. if (sound.soundTrackId) {
  53276. if (sound.soundTrackId === -1) {
  53277. this._scene.mainSoundTrack.RemoveSound(sound);
  53278. }
  53279. else {
  53280. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53281. }
  53282. }
  53283. this.soundCollection.push(sound);
  53284. sound.soundTrackId = this.id;
  53285. };
  53286. SoundTrack.prototype.RemoveSound = function (sound) {
  53287. var index = this.soundCollection.indexOf(sound);
  53288. if (index !== -1) {
  53289. this.soundCollection.splice(index, 1);
  53290. }
  53291. };
  53292. SoundTrack.prototype.setVolume = function (newVolume) {
  53293. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53294. this._outputAudioNode.gain.value = newVolume;
  53295. }
  53296. };
  53297. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53298. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53299. for (var i = 0; i < this.soundCollection.length; i++) {
  53300. this.soundCollection[i].switchPanningModelToHRTF();
  53301. }
  53302. }
  53303. };
  53304. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53305. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53306. for (var i = 0; i < this.soundCollection.length; i++) {
  53307. this.soundCollection[i].switchPanningModelToEqualPower();
  53308. }
  53309. }
  53310. };
  53311. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53312. if (this._connectedAnalyser) {
  53313. this._connectedAnalyser.stopDebugCanvas();
  53314. }
  53315. this._connectedAnalyser = analyser;
  53316. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53317. this._outputAudioNode.disconnect();
  53318. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53319. }
  53320. };
  53321. return SoundTrack;
  53322. }());
  53323. BABYLON.SoundTrack = SoundTrack;
  53324. })(BABYLON || (BABYLON = {}));
  53325. //# sourceMappingURL=babylon.soundtrack.js.map
  53326. var BABYLON;
  53327. (function (BABYLON) {
  53328. var Analyser = /** @class */ (function () {
  53329. function Analyser(scene) {
  53330. this.SMOOTHING = 0.75;
  53331. this.FFT_SIZE = 512;
  53332. this.BARGRAPHAMPLITUDE = 256;
  53333. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53334. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53335. this._scene = scene;
  53336. this._audioEngine = BABYLON.Engine.audioEngine;
  53337. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  53338. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53339. this._webAudioAnalyser.minDecibels = -140;
  53340. this._webAudioAnalyser.maxDecibels = 0;
  53341. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53342. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53343. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53344. }
  53345. }
  53346. Analyser.prototype.getFrequencyBinCount = function () {
  53347. if (this._audioEngine.canUseWebAudio) {
  53348. return this._webAudioAnalyser.frequencyBinCount;
  53349. }
  53350. else {
  53351. return 0;
  53352. }
  53353. };
  53354. Analyser.prototype.getByteFrequencyData = function () {
  53355. if (this._audioEngine.canUseWebAudio) {
  53356. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53357. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53358. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53359. }
  53360. return this._byteFreqs;
  53361. };
  53362. Analyser.prototype.getByteTimeDomainData = function () {
  53363. if (this._audioEngine.canUseWebAudio) {
  53364. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53365. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53366. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53367. }
  53368. return this._byteTime;
  53369. };
  53370. Analyser.prototype.getFloatFrequencyData = function () {
  53371. if (this._audioEngine.canUseWebAudio) {
  53372. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53373. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53374. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53375. }
  53376. return this._floatFreqs;
  53377. };
  53378. Analyser.prototype.drawDebugCanvas = function () {
  53379. var _this = this;
  53380. if (this._audioEngine.canUseWebAudio) {
  53381. if (!this._debugCanvas) {
  53382. this._debugCanvas = document.createElement("canvas");
  53383. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53384. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53385. this._debugCanvas.style.position = "absolute";
  53386. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53387. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53388. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53389. document.body.appendChild(this._debugCanvas);
  53390. this._registerFunc = function () {
  53391. _this.drawDebugCanvas();
  53392. };
  53393. this._scene.registerBeforeRender(this._registerFunc);
  53394. }
  53395. if (this._registerFunc && this._debugCanvasContext) {
  53396. var workingArray = this.getByteFrequencyData();
  53397. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53398. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53399. // Draw the frequency domain chart.
  53400. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53401. var value = workingArray[i];
  53402. var percent = value / this.BARGRAPHAMPLITUDE;
  53403. var height = this.DEBUGCANVASSIZE.height * percent;
  53404. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53405. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53406. var hue = i / this.getFrequencyBinCount() * 360;
  53407. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53408. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53409. }
  53410. }
  53411. }
  53412. };
  53413. Analyser.prototype.stopDebugCanvas = function () {
  53414. if (this._debugCanvas) {
  53415. if (this._registerFunc) {
  53416. this._scene.unregisterBeforeRender(this._registerFunc);
  53417. this._registerFunc = null;
  53418. }
  53419. document.body.removeChild(this._debugCanvas);
  53420. this._debugCanvas = null;
  53421. this._debugCanvasContext = null;
  53422. }
  53423. };
  53424. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53425. if (this._audioEngine.canUseWebAudio) {
  53426. inputAudioNode.connect(this._webAudioAnalyser);
  53427. this._webAudioAnalyser.connect(outputAudioNode);
  53428. }
  53429. };
  53430. Analyser.prototype.dispose = function () {
  53431. if (this._audioEngine.canUseWebAudio) {
  53432. this._webAudioAnalyser.disconnect();
  53433. }
  53434. };
  53435. return Analyser;
  53436. }());
  53437. BABYLON.Analyser = Analyser;
  53438. })(BABYLON || (BABYLON = {}));
  53439. //# sourceMappingURL=babylon.analyser.js.map
  53440. var BABYLON;
  53441. (function (BABYLON) {
  53442. var CubeTexture = /** @class */ (function (_super) {
  53443. __extends(CubeTexture, _super);
  53444. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53445. if (extensions === void 0) { extensions = null; }
  53446. if (noMipmap === void 0) { noMipmap = false; }
  53447. if (files === void 0) { files = null; }
  53448. if (onLoad === void 0) { onLoad = null; }
  53449. if (onError === void 0) { onError = null; }
  53450. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53451. if (prefiltered === void 0) { prefiltered = false; }
  53452. if (forcedExtension === void 0) { forcedExtension = null; }
  53453. var _this = _super.call(this, scene) || this;
  53454. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53455. _this.name = rootUrl;
  53456. _this.url = rootUrl;
  53457. _this._noMipmap = noMipmap;
  53458. _this.hasAlpha = false;
  53459. _this._format = format;
  53460. _this._prefiltered = prefiltered;
  53461. _this.isCube = true;
  53462. _this._textureMatrix = BABYLON.Matrix.Identity();
  53463. if (prefiltered) {
  53464. _this.gammaSpace = false;
  53465. }
  53466. if (!rootUrl && !files) {
  53467. return _this;
  53468. }
  53469. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53470. var lastDot = rootUrl.lastIndexOf(".");
  53471. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53472. var isDDS = (extension === ".dds");
  53473. if (!files) {
  53474. if (!isDDS && !extensions) {
  53475. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53476. }
  53477. files = [];
  53478. if (extensions) {
  53479. for (var index = 0; index < extensions.length; index++) {
  53480. files.push(rootUrl + extensions[index]);
  53481. }
  53482. }
  53483. }
  53484. _this._files = files;
  53485. if (!_this._texture) {
  53486. if (!scene.useDelayedTextureLoading) {
  53487. if (prefiltered) {
  53488. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53489. }
  53490. else {
  53491. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53492. }
  53493. }
  53494. else {
  53495. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53496. }
  53497. }
  53498. else if (onLoad) {
  53499. if (_this._texture.isReady) {
  53500. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53501. }
  53502. else {
  53503. _this._texture.onLoadedObservable.add(onLoad);
  53504. }
  53505. }
  53506. return _this;
  53507. }
  53508. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53509. return new CubeTexture("", scene, null, noMipmap, files);
  53510. };
  53511. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53512. if (forcedExtension === void 0) { forcedExtension = null; }
  53513. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53514. };
  53515. // Methods
  53516. CubeTexture.prototype.delayLoad = function () {
  53517. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53518. return;
  53519. }
  53520. var scene = this.getScene();
  53521. if (!scene) {
  53522. return;
  53523. }
  53524. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53525. this._texture = this._getFromCache(this.url, this._noMipmap);
  53526. if (!this._texture) {
  53527. if (this._prefiltered) {
  53528. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53529. }
  53530. else {
  53531. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53532. }
  53533. }
  53534. };
  53535. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53536. return this._textureMatrix;
  53537. };
  53538. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53539. this._textureMatrix = value;
  53540. };
  53541. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53542. var texture = BABYLON.SerializationHelper.Parse(function () {
  53543. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53544. }, parsedTexture, scene);
  53545. // Animations
  53546. if (parsedTexture.animations) {
  53547. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53548. var parsedAnimation = parsedTexture.animations[animationIndex];
  53549. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53550. }
  53551. }
  53552. return texture;
  53553. };
  53554. CubeTexture.prototype.clone = function () {
  53555. var _this = this;
  53556. return BABYLON.SerializationHelper.Clone(function () {
  53557. var scene = _this.getScene();
  53558. if (!scene) {
  53559. return _this;
  53560. }
  53561. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53562. }, this);
  53563. };
  53564. return CubeTexture;
  53565. }(BABYLON.BaseTexture));
  53566. BABYLON.CubeTexture = CubeTexture;
  53567. })(BABYLON || (BABYLON = {}));
  53568. //# sourceMappingURL=babylon.cubeTexture.js.map
  53569. var BABYLON;
  53570. (function (BABYLON) {
  53571. var RenderTargetTexture = /** @class */ (function (_super) {
  53572. __extends(RenderTargetTexture, _super);
  53573. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53574. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53575. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53576. if (isCube === void 0) { isCube = false; }
  53577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53578. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53579. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53580. if (isMulti === void 0) { isMulti = false; }
  53581. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53582. _this.isCube = isCube;
  53583. /**
  53584. * Use this list to define the list of mesh you want to render.
  53585. */
  53586. _this.renderList = new Array();
  53587. _this.renderParticles = true;
  53588. _this.renderSprites = false;
  53589. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53590. _this.ignoreCameraViewport = false;
  53591. // Events
  53592. /**
  53593. * An event triggered when the texture is unbind.
  53594. * @type {BABYLON.Observable}
  53595. */
  53596. _this.onBeforeBindObservable = new BABYLON.Observable();
  53597. /**
  53598. * An event triggered when the texture is unbind.
  53599. * @type {BABYLON.Observable}
  53600. */
  53601. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53602. /**
  53603. * An event triggered before rendering the texture
  53604. * @type {BABYLON.Observable}
  53605. */
  53606. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53607. /**
  53608. * An event triggered after rendering the texture
  53609. * @type {BABYLON.Observable}
  53610. */
  53611. _this.onAfterRenderObservable = new BABYLON.Observable();
  53612. /**
  53613. * An event triggered after the texture clear
  53614. * @type {BABYLON.Observable}
  53615. */
  53616. _this.onClearObservable = new BABYLON.Observable();
  53617. _this._currentRefreshId = -1;
  53618. _this._refreshRate = 1;
  53619. _this._samples = 1;
  53620. scene = _this.getScene();
  53621. if (!scene) {
  53622. return _this;
  53623. }
  53624. _this._engine = scene.getEngine();
  53625. _this.name = name;
  53626. _this.isRenderTarget = true;
  53627. _this._initialSizeParameter = size;
  53628. _this._processSizeParameter(size);
  53629. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53630. });
  53631. _this._generateMipMaps = generateMipMaps ? true : false;
  53632. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53633. // Rendering groups
  53634. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53635. if (isMulti) {
  53636. return _this;
  53637. }
  53638. _this._renderTargetOptions = {
  53639. generateMipMaps: generateMipMaps,
  53640. type: type,
  53641. samplingMode: samplingMode,
  53642. generateDepthBuffer: generateDepthBuffer,
  53643. generateStencilBuffer: generateStencilBuffer
  53644. };
  53645. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53646. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53647. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53648. }
  53649. if (isCube) {
  53650. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53651. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53652. _this._textureMatrix = BABYLON.Matrix.Identity();
  53653. }
  53654. else {
  53655. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53656. }
  53657. return _this;
  53658. }
  53659. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53660. get: function () {
  53661. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53662. },
  53663. enumerable: true,
  53664. configurable: true
  53665. });
  53666. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  53667. get: function () {
  53668. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  53669. },
  53670. enumerable: true,
  53671. configurable: true
  53672. });
  53673. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  53674. get: function () {
  53675. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  53676. },
  53677. enumerable: true,
  53678. configurable: true
  53679. });
  53680. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  53681. set: function (callback) {
  53682. if (this._onAfterUnbindObserver) {
  53683. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  53684. }
  53685. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  53686. },
  53687. enumerable: true,
  53688. configurable: true
  53689. });
  53690. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  53691. set: function (callback) {
  53692. if (this._onBeforeRenderObserver) {
  53693. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53694. }
  53695. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53696. },
  53697. enumerable: true,
  53698. configurable: true
  53699. });
  53700. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  53701. set: function (callback) {
  53702. if (this._onAfterRenderObserver) {
  53703. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53704. }
  53705. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53706. },
  53707. enumerable: true,
  53708. configurable: true
  53709. });
  53710. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  53711. set: function (callback) {
  53712. if (this._onClearObserver) {
  53713. this.onClearObservable.remove(this._onClearObserver);
  53714. }
  53715. this._onClearObserver = this.onClearObservable.add(callback);
  53716. },
  53717. enumerable: true,
  53718. configurable: true
  53719. });
  53720. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  53721. get: function () {
  53722. return this._renderTargetOptions;
  53723. },
  53724. enumerable: true,
  53725. configurable: true
  53726. });
  53727. RenderTargetTexture.prototype._onRatioRescale = function () {
  53728. if (this._sizeRatio) {
  53729. this.resize(this._initialSizeParameter);
  53730. }
  53731. };
  53732. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  53733. if (size.ratio) {
  53734. this._sizeRatio = size.ratio;
  53735. this._size = {
  53736. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  53737. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  53738. };
  53739. }
  53740. else {
  53741. this._size = size;
  53742. }
  53743. };
  53744. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  53745. get: function () {
  53746. return this._samples;
  53747. },
  53748. set: function (value) {
  53749. if (this._samples === value) {
  53750. return;
  53751. }
  53752. var scene = this.getScene();
  53753. if (!scene) {
  53754. return;
  53755. }
  53756. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  53757. },
  53758. enumerable: true,
  53759. configurable: true
  53760. });
  53761. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  53762. this._currentRefreshId = -1;
  53763. };
  53764. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  53765. get: function () {
  53766. return this._refreshRate;
  53767. },
  53768. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53769. set: function (value) {
  53770. this._refreshRate = value;
  53771. this.resetRefreshCounter();
  53772. },
  53773. enumerable: true,
  53774. configurable: true
  53775. });
  53776. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  53777. if (!this._postProcessManager) {
  53778. var scene = this.getScene();
  53779. if (!scene) {
  53780. return;
  53781. }
  53782. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  53783. this._postProcesses = new Array();
  53784. }
  53785. this._postProcesses.push(postProcess);
  53786. this._postProcesses[0].autoClear = false;
  53787. };
  53788. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  53789. if (!this._postProcesses) {
  53790. return;
  53791. }
  53792. if (dispose) {
  53793. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  53794. var postProcess = _a[_i];
  53795. postProcess.dispose();
  53796. }
  53797. }
  53798. this._postProcesses = [];
  53799. };
  53800. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  53801. if (!this._postProcesses) {
  53802. return;
  53803. }
  53804. var index = this._postProcesses.indexOf(postProcess);
  53805. if (index === -1) {
  53806. return;
  53807. }
  53808. this._postProcesses.splice(index, 1);
  53809. if (this._postProcesses.length > 0) {
  53810. this._postProcesses[0].autoClear = false;
  53811. }
  53812. };
  53813. RenderTargetTexture.prototype._shouldRender = function () {
  53814. if (this._currentRefreshId === -1) {
  53815. this._currentRefreshId = 1;
  53816. return true;
  53817. }
  53818. if (this.refreshRate === this._currentRefreshId) {
  53819. this._currentRefreshId = 1;
  53820. return true;
  53821. }
  53822. this._currentRefreshId++;
  53823. return false;
  53824. };
  53825. RenderTargetTexture.prototype.getRenderSize = function () {
  53826. if (this._size.width) {
  53827. return this._size.width;
  53828. }
  53829. return this._size;
  53830. };
  53831. RenderTargetTexture.prototype.getRenderWidth = function () {
  53832. if (this._size.width) {
  53833. return this._size.width;
  53834. }
  53835. return this._size;
  53836. };
  53837. RenderTargetTexture.prototype.getRenderHeight = function () {
  53838. if (this._size.width) {
  53839. return this._size.height;
  53840. }
  53841. return this._size;
  53842. };
  53843. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  53844. get: function () {
  53845. return true;
  53846. },
  53847. enumerable: true,
  53848. configurable: true
  53849. });
  53850. RenderTargetTexture.prototype.scale = function (ratio) {
  53851. var newSize = this.getRenderSize() * ratio;
  53852. this.resize(newSize);
  53853. };
  53854. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  53855. if (this.isCube) {
  53856. return this._textureMatrix;
  53857. }
  53858. return _super.prototype.getReflectionTextureMatrix.call(this);
  53859. };
  53860. RenderTargetTexture.prototype.resize = function (size) {
  53861. this.releaseInternalTexture();
  53862. var scene = this.getScene();
  53863. if (!scene) {
  53864. return;
  53865. }
  53866. this._processSizeParameter(size);
  53867. if (this.isCube) {
  53868. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  53869. }
  53870. else {
  53871. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  53872. }
  53873. };
  53874. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  53875. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  53876. if (dumpForDebug === void 0) { dumpForDebug = false; }
  53877. var scene = this.getScene();
  53878. if (!scene) {
  53879. return;
  53880. }
  53881. var engine = scene.getEngine();
  53882. if (this.useCameraPostProcesses !== undefined) {
  53883. useCameraPostProcess = this.useCameraPostProcesses;
  53884. }
  53885. if (this._waitingRenderList) {
  53886. this.renderList = [];
  53887. for (var index = 0; index < this._waitingRenderList.length; index++) {
  53888. var id = this._waitingRenderList[index];
  53889. var mesh_1 = scene.getMeshByID(id);
  53890. if (mesh_1) {
  53891. this.renderList.push(mesh_1);
  53892. }
  53893. }
  53894. delete this._waitingRenderList;
  53895. }
  53896. // Is predicate defined?
  53897. if (this.renderListPredicate) {
  53898. if (this.renderList) {
  53899. this.renderList.splice(0); // Clear previous renderList
  53900. }
  53901. else {
  53902. this.renderList = [];
  53903. }
  53904. var scene = this.getScene();
  53905. if (!scene) {
  53906. return;
  53907. }
  53908. var sceneMeshes = scene.meshes;
  53909. for (var index = 0; index < sceneMeshes.length; index++) {
  53910. var mesh = sceneMeshes[index];
  53911. if (this.renderListPredicate(mesh)) {
  53912. this.renderList.push(mesh);
  53913. }
  53914. }
  53915. }
  53916. this.onBeforeBindObservable.notifyObservers(this);
  53917. // Set custom projection.
  53918. // Needs to be before binding to prevent changing the aspect ratio.
  53919. var camera;
  53920. if (this.activeCamera) {
  53921. camera = this.activeCamera;
  53922. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53923. if (this.activeCamera !== scene.activeCamera) {
  53924. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  53925. }
  53926. }
  53927. else {
  53928. camera = scene.activeCamera;
  53929. if (camera) {
  53930. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  53931. }
  53932. }
  53933. // Prepare renderingManager
  53934. this._renderingManager.reset();
  53935. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  53936. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  53937. var sceneRenderId = scene.getRenderId();
  53938. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  53939. var mesh = currentRenderList[meshIndex];
  53940. if (mesh) {
  53941. if (!mesh.isReady()) {
  53942. // Reset _currentRefreshId
  53943. this.resetRefreshCounter();
  53944. continue;
  53945. }
  53946. mesh._preActivateForIntermediateRendering(sceneRenderId);
  53947. var isMasked = void 0;
  53948. if (!this.renderList && camera) {
  53949. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  53950. }
  53951. else {
  53952. isMasked = false;
  53953. }
  53954. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  53955. mesh._activate(sceneRenderId);
  53956. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  53957. var subMesh = mesh.subMeshes[subIndex];
  53958. scene._activeIndices.addCount(subMesh.indexCount, false);
  53959. this._renderingManager.dispatch(subMesh, mesh);
  53960. }
  53961. }
  53962. }
  53963. }
  53964. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  53965. var particleSystem = scene.particleSystems[particleIndex];
  53966. var emitter = particleSystem.emitter;
  53967. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  53968. continue;
  53969. }
  53970. if (currentRenderList.indexOf(emitter) >= 0) {
  53971. this._renderingManager.dispatchParticles(particleSystem);
  53972. }
  53973. }
  53974. if (this.isCube) {
  53975. for (var face = 0; face < 6; face++) {
  53976. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53977. scene.incrementRenderId();
  53978. scene.resetCachedMaterial();
  53979. }
  53980. }
  53981. else {
  53982. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  53983. }
  53984. this.onAfterUnbindObservable.notifyObservers(this);
  53985. if (scene.activeCamera) {
  53986. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  53987. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  53988. }
  53989. engine.setViewport(scene.activeCamera.viewport);
  53990. }
  53991. scene.resetCachedMaterial();
  53992. };
  53993. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  53994. var minimum = 128;
  53995. var x = renderDimension * scale;
  53996. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  53997. // Ensure we don't exceed the render dimension (while staying POT)
  53998. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  53999. };
  54000. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54001. var _this = this;
  54002. if (!this._texture) {
  54003. return;
  54004. }
  54005. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54006. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54007. });
  54008. };
  54009. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54010. var scene = this.getScene();
  54011. if (!scene) {
  54012. return;
  54013. }
  54014. var engine = scene.getEngine();
  54015. if (!this._texture) {
  54016. return;
  54017. }
  54018. // Bind
  54019. if (this._postProcessManager) {
  54020. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54021. }
  54022. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54023. if (this._texture) {
  54024. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54025. }
  54026. }
  54027. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54028. // Clear
  54029. if (this.onClearObservable.hasObservers()) {
  54030. this.onClearObservable.notifyObservers(engine);
  54031. }
  54032. else {
  54033. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54034. }
  54035. if (!this._doNotChangeAspectRatio) {
  54036. scene.updateTransformMatrix(true);
  54037. }
  54038. // Render
  54039. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54040. if (this._postProcessManager) {
  54041. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54042. }
  54043. else if (useCameraPostProcess) {
  54044. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54045. }
  54046. if (!this._doNotChangeAspectRatio) {
  54047. scene.updateTransformMatrix(true);
  54048. }
  54049. // Dump ?
  54050. if (dumpForDebug) {
  54051. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54052. }
  54053. // Unbind
  54054. if (!this.isCube || faceIndex === 5) {
  54055. if (this.isCube) {
  54056. if (faceIndex === 5) {
  54057. engine.generateMipMapsForCubemap(this._texture);
  54058. }
  54059. }
  54060. this.unbindFrameBuffer(engine, faceIndex);
  54061. }
  54062. else {
  54063. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54064. }
  54065. };
  54066. /**
  54067. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54068. * This allowed control for front to back rendering or reversly depending of the special needs.
  54069. *
  54070. * @param renderingGroupId The rendering group id corresponding to its index
  54071. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54072. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54073. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54074. */
  54075. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54076. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54077. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54078. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54079. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54080. };
  54081. /**
  54082. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54083. *
  54084. * @param renderingGroupId The rendering group id corresponding to its index
  54085. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54086. */
  54087. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54088. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54089. };
  54090. RenderTargetTexture.prototype.clone = function () {
  54091. var textureSize = this.getSize();
  54092. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  54093. // Base texture
  54094. newTexture.hasAlpha = this.hasAlpha;
  54095. newTexture.level = this.level;
  54096. // RenderTarget Texture
  54097. newTexture.coordinatesMode = this.coordinatesMode;
  54098. if (this.renderList) {
  54099. newTexture.renderList = this.renderList.slice(0);
  54100. }
  54101. return newTexture;
  54102. };
  54103. RenderTargetTexture.prototype.serialize = function () {
  54104. if (!this.name) {
  54105. return null;
  54106. }
  54107. var serializationObject = _super.prototype.serialize.call(this);
  54108. serializationObject.renderTargetSize = this.getRenderSize();
  54109. serializationObject.renderList = [];
  54110. if (this.renderList) {
  54111. for (var index = 0; index < this.renderList.length; index++) {
  54112. serializationObject.renderList.push(this.renderList[index].id);
  54113. }
  54114. }
  54115. return serializationObject;
  54116. };
  54117. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54118. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54119. var objBuffer = this.getInternalTexture();
  54120. var scene = this.getScene();
  54121. if (objBuffer && scene) {
  54122. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54123. }
  54124. };
  54125. RenderTargetTexture.prototype.dispose = function () {
  54126. if (this._postProcessManager) {
  54127. this._postProcessManager.dispose();
  54128. this._postProcessManager = null;
  54129. }
  54130. this.clearPostProcesses(true);
  54131. if (this._resizeObserver) {
  54132. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54133. this._resizeObserver = null;
  54134. }
  54135. this.renderList = null;
  54136. // Remove from custom render targets
  54137. var scene = this.getScene();
  54138. if (!scene) {
  54139. return;
  54140. }
  54141. var index = scene.customRenderTargets.indexOf(this);
  54142. if (index >= 0) {
  54143. scene.customRenderTargets.splice(index, 1);
  54144. }
  54145. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  54146. var camera = _a[_i];
  54147. index = camera.customRenderTargets.indexOf(this);
  54148. if (index >= 0) {
  54149. camera.customRenderTargets.splice(index, 1);
  54150. }
  54151. }
  54152. _super.prototype.dispose.call(this);
  54153. };
  54154. RenderTargetTexture.prototype._rebuild = function () {
  54155. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54156. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54157. }
  54158. if (this._postProcessManager) {
  54159. this._postProcessManager._rebuild();
  54160. }
  54161. };
  54162. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  54163. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  54164. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  54165. return RenderTargetTexture;
  54166. }(BABYLON.Texture));
  54167. BABYLON.RenderTargetTexture = RenderTargetTexture;
  54168. })(BABYLON || (BABYLON = {}));
  54169. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  54170. var BABYLON;
  54171. (function (BABYLON) {
  54172. ;
  54173. var MultiRenderTarget = /** @class */ (function (_super) {
  54174. __extends(MultiRenderTarget, _super);
  54175. function MultiRenderTarget(name, size, count, scene, options) {
  54176. var _this = this;
  54177. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  54178. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  54179. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  54180. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  54181. _this._engine = scene.getEngine();
  54182. if (!_this.isSupported) {
  54183. _this.dispose();
  54184. return;
  54185. }
  54186. var types = [];
  54187. var samplingModes = [];
  54188. for (var i = 0; i < count; i++) {
  54189. if (options && options.types && options.types[i] !== undefined) {
  54190. types.push(options.types[i]);
  54191. }
  54192. else {
  54193. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54194. }
  54195. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  54196. samplingModes.push(options.samplingModes[i]);
  54197. }
  54198. else {
  54199. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54200. }
  54201. }
  54202. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  54203. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  54204. _this._size = size;
  54205. _this._multiRenderTargetOptions = {
  54206. samplingModes: samplingModes,
  54207. generateMipMaps: generateMipMaps,
  54208. generateDepthBuffer: generateDepthBuffer,
  54209. generateStencilBuffer: generateStencilBuffer,
  54210. generateDepthTexture: generateDepthTexture,
  54211. types: types,
  54212. textureCount: count
  54213. };
  54214. _this._createInternalTextures();
  54215. _this._createTextures();
  54216. return _this;
  54217. }
  54218. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  54219. get: function () {
  54220. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  54221. },
  54222. enumerable: true,
  54223. configurable: true
  54224. });
  54225. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  54226. get: function () {
  54227. return this._textures;
  54228. },
  54229. enumerable: true,
  54230. configurable: true
  54231. });
  54232. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  54233. get: function () {
  54234. return this._textures[this._textures.length - 1];
  54235. },
  54236. enumerable: true,
  54237. configurable: true
  54238. });
  54239. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  54240. set: function (wrap) {
  54241. if (this._textures) {
  54242. for (var i = 0; i < this._textures.length; i++) {
  54243. this._textures[i].wrapU = wrap;
  54244. }
  54245. }
  54246. },
  54247. enumerable: true,
  54248. configurable: true
  54249. });
  54250. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  54251. set: function (wrap) {
  54252. if (this._textures) {
  54253. for (var i = 0; i < this._textures.length; i++) {
  54254. this._textures[i].wrapV = wrap;
  54255. }
  54256. }
  54257. },
  54258. enumerable: true,
  54259. configurable: true
  54260. });
  54261. MultiRenderTarget.prototype._rebuild = function () {
  54262. this.releaseInternalTextures();
  54263. this._createInternalTextures();
  54264. for (var i = 0; i < this._internalTextures.length; i++) {
  54265. var texture = this._textures[i];
  54266. texture._texture = this._internalTextures[i];
  54267. }
  54268. // Keeps references to frame buffer and stencil/depth buffer
  54269. this._texture = this._internalTextures[0];
  54270. };
  54271. MultiRenderTarget.prototype._createInternalTextures = function () {
  54272. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54273. };
  54274. MultiRenderTarget.prototype._createTextures = function () {
  54275. this._textures = [];
  54276. for (var i = 0; i < this._internalTextures.length; i++) {
  54277. var texture = new BABYLON.Texture(null, this.getScene());
  54278. texture._texture = this._internalTextures[i];
  54279. this._textures.push(texture);
  54280. }
  54281. // Keeps references to frame buffer and stencil/depth buffer
  54282. this._texture = this._internalTextures[0];
  54283. };
  54284. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54285. get: function () {
  54286. return this._samples;
  54287. },
  54288. set: function (value) {
  54289. if (this._samples === value) {
  54290. return;
  54291. }
  54292. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54293. },
  54294. enumerable: true,
  54295. configurable: true
  54296. });
  54297. MultiRenderTarget.prototype.resize = function (size) {
  54298. this.releaseInternalTextures();
  54299. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54300. this._createInternalTextures();
  54301. };
  54302. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54303. var _this = this;
  54304. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54305. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54306. });
  54307. };
  54308. MultiRenderTarget.prototype.dispose = function () {
  54309. this.releaseInternalTextures();
  54310. _super.prototype.dispose.call(this);
  54311. };
  54312. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54313. if (!this._internalTextures) {
  54314. return;
  54315. }
  54316. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54317. if (this._internalTextures[i] !== undefined) {
  54318. this._internalTextures[i].dispose();
  54319. this._internalTextures.splice(i, 1);
  54320. }
  54321. }
  54322. };
  54323. return MultiRenderTarget;
  54324. }(BABYLON.RenderTargetTexture));
  54325. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54326. })(BABYLON || (BABYLON = {}));
  54327. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  54328. var BABYLON;
  54329. (function (BABYLON) {
  54330. var MirrorTexture = /** @class */ (function (_super) {
  54331. __extends(MirrorTexture, _super);
  54332. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  54333. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54334. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54335. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54336. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  54337. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  54338. _this._transformMatrix = BABYLON.Matrix.Zero();
  54339. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  54340. _this._adaptiveBlurKernel = 0;
  54341. _this._blurKernelX = 0;
  54342. _this._blurKernelY = 0;
  54343. _this._blurRatio = 1.0;
  54344. _this.ignoreCameraViewport = true;
  54345. _this.onBeforeRenderObservable.add(function () {
  54346. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  54347. _this._savedViewMatrix = scene.getViewMatrix();
  54348. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  54349. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  54350. scene.clipPlane = _this.mirrorPlane;
  54351. scene.getEngine().cullBackFaces = false;
  54352. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  54353. });
  54354. _this.onAfterRenderObservable.add(function () {
  54355. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  54356. scene.getEngine().cullBackFaces = true;
  54357. scene._mirroredCameraPosition = null;
  54358. delete scene.clipPlane;
  54359. });
  54360. return _this;
  54361. }
  54362. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  54363. get: function () {
  54364. return this._blurRatio;
  54365. },
  54366. set: function (value) {
  54367. if (this._blurRatio === value) {
  54368. return;
  54369. }
  54370. this._blurRatio = value;
  54371. this._preparePostProcesses();
  54372. },
  54373. enumerable: true,
  54374. configurable: true
  54375. });
  54376. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  54377. set: function (value) {
  54378. this._adaptiveBlurKernel = value;
  54379. this._autoComputeBlurKernel();
  54380. },
  54381. enumerable: true,
  54382. configurable: true
  54383. });
  54384. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  54385. set: function (value) {
  54386. this.blurKernelX = value;
  54387. this.blurKernelY = value;
  54388. },
  54389. enumerable: true,
  54390. configurable: true
  54391. });
  54392. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  54393. get: function () {
  54394. return this._blurKernelX;
  54395. },
  54396. set: function (value) {
  54397. if (this._blurKernelX === value) {
  54398. return;
  54399. }
  54400. this._blurKernelX = value;
  54401. this._preparePostProcesses();
  54402. },
  54403. enumerable: true,
  54404. configurable: true
  54405. });
  54406. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  54407. get: function () {
  54408. return this._blurKernelY;
  54409. },
  54410. set: function (value) {
  54411. if (this._blurKernelY === value) {
  54412. return;
  54413. }
  54414. this._blurKernelY = value;
  54415. this._preparePostProcesses();
  54416. },
  54417. enumerable: true,
  54418. configurable: true
  54419. });
  54420. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  54421. var engine = this.getScene().getEngine();
  54422. var dw = this.getRenderWidth() / engine.getRenderWidth();
  54423. var dh = this.getRenderHeight() / engine.getRenderHeight();
  54424. this.blurKernelX = this._adaptiveBlurKernel * dw;
  54425. this.blurKernelY = this._adaptiveBlurKernel * dh;
  54426. };
  54427. MirrorTexture.prototype._onRatioRescale = function () {
  54428. if (this._sizeRatio) {
  54429. this.resize(this._initialSizeParameter);
  54430. if (!this._adaptiveBlurKernel) {
  54431. this._preparePostProcesses();
  54432. }
  54433. }
  54434. if (this._adaptiveBlurKernel) {
  54435. this._autoComputeBlurKernel();
  54436. }
  54437. };
  54438. MirrorTexture.prototype._preparePostProcesses = function () {
  54439. this.clearPostProcesses(true);
  54440. if (this._blurKernelX && this._blurKernelY) {
  54441. var engine = this.getScene().getEngine();
  54442. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54443. 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);
  54444. this._blurX.autoClear = false;
  54445. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54446. this._blurX.outputTexture = this._texture;
  54447. }
  54448. else {
  54449. this._blurX.alwaysForcePOT = true;
  54450. }
  54451. 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);
  54452. this._blurY.autoClear = false;
  54453. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54454. this.addPostProcess(this._blurX);
  54455. this.addPostProcess(this._blurY);
  54456. }
  54457. else {
  54458. if (this._blurY) {
  54459. this.removePostProcess(this._blurY);
  54460. this._blurY.dispose();
  54461. this._blurY = null;
  54462. }
  54463. if (this._blurX) {
  54464. this.removePostProcess(this._blurX);
  54465. this._blurX.dispose();
  54466. this._blurX = null;
  54467. }
  54468. }
  54469. };
  54470. MirrorTexture.prototype.clone = function () {
  54471. var scene = this.getScene();
  54472. if (!scene) {
  54473. return this;
  54474. }
  54475. var textureSize = this.getSize();
  54476. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54477. // Base texture
  54478. newTexture.hasAlpha = this.hasAlpha;
  54479. newTexture.level = this.level;
  54480. // Mirror Texture
  54481. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54482. if (this.renderList) {
  54483. newTexture.renderList = this.renderList.slice(0);
  54484. }
  54485. return newTexture;
  54486. };
  54487. MirrorTexture.prototype.serialize = function () {
  54488. if (!this.name) {
  54489. return null;
  54490. }
  54491. var serializationObject = _super.prototype.serialize.call(this);
  54492. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54493. return serializationObject;
  54494. };
  54495. return MirrorTexture;
  54496. }(BABYLON.RenderTargetTexture));
  54497. BABYLON.MirrorTexture = MirrorTexture;
  54498. })(BABYLON || (BABYLON = {}));
  54499. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54500. var BABYLON;
  54501. (function (BABYLON) {
  54502. /**
  54503. * Creates a refraction texture used by refraction channel of the standard material.
  54504. * @param name the texture name
  54505. * @param size size of the underlying texture
  54506. * @param scene root scene
  54507. */
  54508. var RefractionTexture = /** @class */ (function (_super) {
  54509. __extends(RefractionTexture, _super);
  54510. function RefractionTexture(name, size, scene, generateMipMaps) {
  54511. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54512. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54513. _this.depth = 2.0;
  54514. _this.onBeforeRenderObservable.add(function () {
  54515. scene.clipPlane = _this.refractionPlane;
  54516. });
  54517. _this.onAfterRenderObservable.add(function () {
  54518. delete scene.clipPlane;
  54519. });
  54520. return _this;
  54521. }
  54522. RefractionTexture.prototype.clone = function () {
  54523. var scene = this.getScene();
  54524. if (!scene) {
  54525. return this;
  54526. }
  54527. var textureSize = this.getSize();
  54528. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54529. // Base texture
  54530. newTexture.hasAlpha = this.hasAlpha;
  54531. newTexture.level = this.level;
  54532. // Refraction Texture
  54533. newTexture.refractionPlane = this.refractionPlane.clone();
  54534. if (this.renderList) {
  54535. newTexture.renderList = this.renderList.slice(0);
  54536. }
  54537. newTexture.depth = this.depth;
  54538. return newTexture;
  54539. };
  54540. RefractionTexture.prototype.serialize = function () {
  54541. if (!this.name) {
  54542. return null;
  54543. }
  54544. var serializationObject = _super.prototype.serialize.call(this);
  54545. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54546. serializationObject.depth = this.depth;
  54547. return serializationObject;
  54548. };
  54549. return RefractionTexture;
  54550. }(BABYLON.RenderTargetTexture));
  54551. BABYLON.RefractionTexture = RefractionTexture;
  54552. })(BABYLON || (BABYLON = {}));
  54553. //# sourceMappingURL=babylon.refractionTexture.js.map
  54554. var BABYLON;
  54555. (function (BABYLON) {
  54556. var DynamicTexture = /** @class */ (function (_super) {
  54557. __extends(DynamicTexture, _super);
  54558. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54559. if (scene === void 0) { scene = null; }
  54560. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54561. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54562. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54563. _this.name = name;
  54564. _this._engine = _this.getScene().getEngine();
  54565. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54566. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54567. _this._generateMipMaps = generateMipMaps;
  54568. if (options.getContext) {
  54569. _this._canvas = options;
  54570. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54571. }
  54572. else {
  54573. _this._canvas = document.createElement("canvas");
  54574. if (options.width) {
  54575. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54576. }
  54577. else {
  54578. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54579. }
  54580. }
  54581. var textureSize = _this.getSize();
  54582. _this._canvas.width = textureSize.width;
  54583. _this._canvas.height = textureSize.height;
  54584. _this._context = _this._canvas.getContext("2d");
  54585. return _this;
  54586. }
  54587. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54588. get: function () {
  54589. return true;
  54590. },
  54591. enumerable: true,
  54592. configurable: true
  54593. });
  54594. DynamicTexture.prototype._recreate = function (textureSize) {
  54595. this._canvas.width = textureSize.width;
  54596. this._canvas.height = textureSize.height;
  54597. this.releaseInternalTexture();
  54598. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54599. };
  54600. DynamicTexture.prototype.scale = function (ratio) {
  54601. var textureSize = this.getSize();
  54602. textureSize.width *= ratio;
  54603. textureSize.height *= ratio;
  54604. this._recreate(textureSize);
  54605. };
  54606. DynamicTexture.prototype.scaleTo = function (width, height) {
  54607. var textureSize = this.getSize();
  54608. textureSize.width = width;
  54609. textureSize.height = height;
  54610. this._recreate(textureSize);
  54611. };
  54612. DynamicTexture.prototype.getContext = function () {
  54613. return this._context;
  54614. };
  54615. DynamicTexture.prototype.clear = function () {
  54616. var size = this.getSize();
  54617. this._context.fillRect(0, 0, size.width, size.height);
  54618. };
  54619. DynamicTexture.prototype.update = function (invertY) {
  54620. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54621. };
  54622. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54623. if (update === void 0) { update = true; }
  54624. var size = this.getSize();
  54625. if (clearColor) {
  54626. this._context.fillStyle = clearColor;
  54627. this._context.fillRect(0, 0, size.width, size.height);
  54628. }
  54629. this._context.font = font;
  54630. if (x === null || x === undefined) {
  54631. var textSize = this._context.measureText(text);
  54632. x = (size.width - textSize.width) / 2;
  54633. }
  54634. if (y === null || y === undefined) {
  54635. var fontSize = parseInt((font.replace(/\D/g, '')));
  54636. ;
  54637. y = (size.height / 2) + (fontSize / 3.65);
  54638. }
  54639. this._context.fillStyle = color;
  54640. this._context.fillText(text, x, y);
  54641. if (update) {
  54642. this.update(invertY);
  54643. }
  54644. };
  54645. DynamicTexture.prototype.clone = function () {
  54646. var scene = this.getScene();
  54647. if (!scene) {
  54648. return this;
  54649. }
  54650. var textureSize = this.getSize();
  54651. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54652. // Base texture
  54653. newTexture.hasAlpha = this.hasAlpha;
  54654. newTexture.level = this.level;
  54655. // Dynamic Texture
  54656. newTexture.wrapU = this.wrapU;
  54657. newTexture.wrapV = this.wrapV;
  54658. return newTexture;
  54659. };
  54660. DynamicTexture.prototype._rebuild = function () {
  54661. this.update();
  54662. };
  54663. return DynamicTexture;
  54664. }(BABYLON.Texture));
  54665. BABYLON.DynamicTexture = DynamicTexture;
  54666. })(BABYLON || (BABYLON = {}));
  54667. //# sourceMappingURL=babylon.dynamicTexture.js.map
  54668. var BABYLON;
  54669. (function (BABYLON) {
  54670. var VideoTexture = /** @class */ (function (_super) {
  54671. __extends(VideoTexture, _super);
  54672. /**
  54673. * Creates a video texture.
  54674. * Sample : https://doc.babylonjs.com/how_to/video_texture
  54675. * @param {string | null} name optional name, will detect from video source, if not defined
  54676. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  54677. * @param {BABYLON.Scene} scene is obviously the current scene.
  54678. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  54679. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  54680. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  54681. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  54682. */
  54683. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  54684. if (generateMipMaps === void 0) { generateMipMaps = false; }
  54685. if (invertY === void 0) { invertY = false; }
  54686. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54687. if (settings === void 0) { settings = {
  54688. autoPlay: true,
  54689. loop: true,
  54690. autoUpdateTexture: true,
  54691. }; }
  54692. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54693. _this._createInternalTexture = function () {
  54694. if (_this._texture != null) {
  54695. return;
  54696. }
  54697. if (!_this._engine.needPOTTextures ||
  54698. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  54699. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54700. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54701. }
  54702. else {
  54703. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54704. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54705. _this._generateMipMaps = false;
  54706. }
  54707. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  54708. _this._texture.isReady = true;
  54709. _this._updateInternalTexture();
  54710. };
  54711. _this.reset = function () {
  54712. if (_this._texture == null) {
  54713. return;
  54714. }
  54715. _this._texture.dispose();
  54716. _this._texture = null;
  54717. };
  54718. _this._updateInternalTexture = function (e) {
  54719. if (_this._texture == null || !_this._texture.isReady) {
  54720. return;
  54721. }
  54722. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  54723. return;
  54724. }
  54725. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  54726. };
  54727. _this._engine = _this.getScene().getEngine();
  54728. _this._generateMipMaps = generateMipMaps;
  54729. _this._samplingMode = samplingMode;
  54730. _this.autoUpdateTexture = settings.autoUpdateTexture;
  54731. _this.name = name || _this._getName(src);
  54732. _this.video = _this._getVideo(src);
  54733. if (settings.autoPlay !== undefined) {
  54734. _this.video.autoplay = settings.autoPlay;
  54735. }
  54736. if (settings.loop !== undefined) {
  54737. _this.video.loop = settings.loop;
  54738. }
  54739. _this.video.addEventListener("canplay", _this._createInternalTexture);
  54740. _this.video.addEventListener("paused", _this._updateInternalTexture);
  54741. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  54742. _this.video.addEventListener("emptied", _this.reset);
  54743. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  54744. _this._createInternalTexture();
  54745. }
  54746. return _this;
  54747. }
  54748. VideoTexture.prototype._getName = function (src) {
  54749. if (src instanceof HTMLVideoElement) {
  54750. return src.currentSrc;
  54751. }
  54752. if (typeof src === "object") {
  54753. return src.toString();
  54754. }
  54755. return src;
  54756. };
  54757. ;
  54758. VideoTexture.prototype._getVideo = function (src) {
  54759. if (src instanceof HTMLVideoElement) {
  54760. return src;
  54761. }
  54762. var video = document.createElement("video");
  54763. if (typeof src === "string") {
  54764. video.src = src;
  54765. }
  54766. else {
  54767. src.forEach(function (url) {
  54768. var source = document.createElement("source");
  54769. source.src = url;
  54770. video.appendChild(source);
  54771. });
  54772. }
  54773. return video;
  54774. };
  54775. ;
  54776. /**
  54777. * Internal method to initiate `update`.
  54778. */
  54779. VideoTexture.prototype._rebuild = function () {
  54780. this.update();
  54781. };
  54782. /**
  54783. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  54784. */
  54785. VideoTexture.prototype.update = function () {
  54786. if (!this.autoUpdateTexture) {
  54787. // Expecting user to call `updateTexture` manually
  54788. return;
  54789. }
  54790. this.updateTexture(true);
  54791. };
  54792. /**
  54793. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  54794. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  54795. */
  54796. VideoTexture.prototype.updateTexture = function (isVisible) {
  54797. if (!isVisible) {
  54798. return;
  54799. }
  54800. if (this.video.paused) {
  54801. return;
  54802. }
  54803. this._updateInternalTexture();
  54804. };
  54805. /**
  54806. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  54807. * @param url New url.
  54808. */
  54809. VideoTexture.prototype.updateURL = function (url) {
  54810. this.video.src = url;
  54811. };
  54812. VideoTexture.prototype.dispose = function () {
  54813. _super.prototype.dispose.call(this);
  54814. this.video.removeEventListener("canplay", this._createInternalTexture);
  54815. this.video.removeEventListener("paused", this._updateInternalTexture);
  54816. this.video.removeEventListener("seeked", this._updateInternalTexture);
  54817. this.video.removeEventListener("emptied", this.reset);
  54818. };
  54819. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  54820. var video = document.createElement("video");
  54821. var constraintsDeviceId;
  54822. if (constraints && constraints.deviceId) {
  54823. constraintsDeviceId = {
  54824. exact: constraints.deviceId,
  54825. };
  54826. }
  54827. navigator.getUserMedia =
  54828. navigator.getUserMedia ||
  54829. navigator.webkitGetUserMedia ||
  54830. navigator.mozGetUserMedia ||
  54831. navigator.msGetUserMedia;
  54832. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  54833. if (navigator.getUserMedia) {
  54834. navigator.getUserMedia({
  54835. video: {
  54836. deviceId: constraintsDeviceId,
  54837. width: {
  54838. min: (constraints && constraints.minWidth) || 256,
  54839. max: (constraints && constraints.maxWidth) || 640,
  54840. },
  54841. height: {
  54842. min: (constraints && constraints.minHeight) || 256,
  54843. max: (constraints && constraints.maxHeight) || 480,
  54844. },
  54845. },
  54846. }, function (stream) {
  54847. if (video.mozSrcObject !== undefined) {
  54848. // hack for Firefox < 19
  54849. video.mozSrcObject = stream;
  54850. }
  54851. else {
  54852. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  54853. }
  54854. video.play();
  54855. if (onReady) {
  54856. onReady(new VideoTexture("video", video, scene, true, true));
  54857. }
  54858. }, function (e) {
  54859. BABYLON.Tools.Error(e.name);
  54860. });
  54861. }
  54862. };
  54863. return VideoTexture;
  54864. }(BABYLON.Texture));
  54865. BABYLON.VideoTexture = VideoTexture;
  54866. })(BABYLON || (BABYLON = {}));
  54867. //# sourceMappingURL=babylon.videoTexture.js.map
  54868. var BABYLON;
  54869. (function (BABYLON) {
  54870. var RawTexture = /** @class */ (function (_super) {
  54871. __extends(RawTexture, _super);
  54872. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  54873. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54874. if (invertY === void 0) { invertY = false; }
  54875. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54876. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54877. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54878. _this.format = format;
  54879. _this._engine = scene.getEngine();
  54880. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  54881. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54882. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54883. return _this;
  54884. }
  54885. RawTexture.prototype.update = function (data) {
  54886. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  54887. };
  54888. // Statics
  54889. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54890. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54891. if (invertY === void 0) { invertY = false; }
  54892. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54893. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54894. };
  54895. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54896. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54897. if (invertY === void 0) { invertY = false; }
  54898. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54899. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54900. };
  54901. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54902. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54903. if (invertY === void 0) { invertY = false; }
  54904. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54905. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  54906. };
  54907. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54908. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54909. if (invertY === void 0) { invertY = false; }
  54910. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54911. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54912. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  54913. };
  54914. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  54915. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54916. if (invertY === void 0) { invertY = false; }
  54917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54918. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54919. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  54920. };
  54921. return RawTexture;
  54922. }(BABYLON.Texture));
  54923. BABYLON.RawTexture = RawTexture;
  54924. })(BABYLON || (BABYLON = {}));
  54925. //# sourceMappingURL=babylon.rawTexture.js.map
  54926. var BABYLON;
  54927. (function (BABYLON) {
  54928. var PostProcess = /** @class */ (function () {
  54929. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  54930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  54931. if (defines === void 0) { defines = null; }
  54932. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54933. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  54934. if (blockCompilation === void 0) { blockCompilation = false; }
  54935. this.name = name;
  54936. this.width = -1;
  54937. this.height = -1;
  54938. this.autoClear = true;
  54939. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  54940. this.animations = new Array();
  54941. /*
  54942. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  54943. Can only be used on a single postprocess or on the last one of a chain.
  54944. */
  54945. this.enablePixelPerfectMode = false;
  54946. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  54947. this.alwaysForcePOT = false;
  54948. this.samples = 1;
  54949. this.adaptScaleToCurrentViewport = false;
  54950. this._reusable = false;
  54951. this._textures = new BABYLON.SmartArray(2);
  54952. this._currentRenderTextureInd = 0;
  54953. this._scaleRatio = new BABYLON.Vector2(1, 1);
  54954. this._texelSize = BABYLON.Vector2.Zero();
  54955. // Events
  54956. /**
  54957. * An event triggered when the postprocess is activated.
  54958. * @type {BABYLON.Observable}
  54959. */
  54960. this.onActivateObservable = new BABYLON.Observable();
  54961. /**
  54962. * An event triggered when the postprocess changes its size.
  54963. * @type {BABYLON.Observable}
  54964. */
  54965. this.onSizeChangedObservable = new BABYLON.Observable();
  54966. /**
  54967. * An event triggered when the postprocess applies its effect.
  54968. * @type {BABYLON.Observable}
  54969. */
  54970. this.onApplyObservable = new BABYLON.Observable();
  54971. /**
  54972. * An event triggered before rendering the postprocess
  54973. * @type {BABYLON.Observable}
  54974. */
  54975. this.onBeforeRenderObservable = new BABYLON.Observable();
  54976. /**
  54977. * An event triggered after rendering the postprocess
  54978. * @type {BABYLON.Observable}
  54979. */
  54980. this.onAfterRenderObservable = new BABYLON.Observable();
  54981. if (camera != null) {
  54982. this._camera = camera;
  54983. this._scene = camera.getScene();
  54984. camera.attachPostProcess(this);
  54985. this._engine = this._scene.getEngine();
  54986. this._scene.postProcesses.push(this);
  54987. }
  54988. else if (engine) {
  54989. this._engine = engine;
  54990. this._engine.postProcesses.push(this);
  54991. }
  54992. this._options = options;
  54993. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  54994. this._reusable = reusable || false;
  54995. this._textureType = textureType;
  54996. this._samplers = samplers || [];
  54997. this._samplers.push("textureSampler");
  54998. this._fragmentUrl = fragmentUrl;
  54999. this._vertexUrl = vertexUrl;
  55000. this._parameters = parameters || [];
  55001. this._parameters.push("scale");
  55002. this._indexParameters = indexParameters;
  55003. if (!blockCompilation) {
  55004. this.updateEffect(defines);
  55005. }
  55006. }
  55007. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55008. set: function (callback) {
  55009. if (this._onActivateObserver) {
  55010. this.onActivateObservable.remove(this._onActivateObserver);
  55011. }
  55012. if (callback) {
  55013. this._onActivateObserver = this.onActivateObservable.add(callback);
  55014. }
  55015. },
  55016. enumerable: true,
  55017. configurable: true
  55018. });
  55019. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55020. set: function (callback) {
  55021. if (this._onSizeChangedObserver) {
  55022. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55023. }
  55024. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55025. },
  55026. enumerable: true,
  55027. configurable: true
  55028. });
  55029. Object.defineProperty(PostProcess.prototype, "onApply", {
  55030. set: function (callback) {
  55031. if (this._onApplyObserver) {
  55032. this.onApplyObservable.remove(this._onApplyObserver);
  55033. }
  55034. this._onApplyObserver = this.onApplyObservable.add(callback);
  55035. },
  55036. enumerable: true,
  55037. configurable: true
  55038. });
  55039. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55040. set: function (callback) {
  55041. if (this._onBeforeRenderObserver) {
  55042. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55043. }
  55044. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55045. },
  55046. enumerable: true,
  55047. configurable: true
  55048. });
  55049. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55050. set: function (callback) {
  55051. if (this._onAfterRenderObserver) {
  55052. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55053. }
  55054. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55055. },
  55056. enumerable: true,
  55057. configurable: true
  55058. });
  55059. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55060. get: function () {
  55061. return this._textures.data[this._currentRenderTextureInd];
  55062. },
  55063. set: function (value) {
  55064. this._forcedOutputTexture = value;
  55065. },
  55066. enumerable: true,
  55067. configurable: true
  55068. });
  55069. PostProcess.prototype.getCamera = function () {
  55070. return this._camera;
  55071. };
  55072. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55073. get: function () {
  55074. if (this._shareOutputWithPostProcess) {
  55075. return this._shareOutputWithPostProcess.texelSize;
  55076. }
  55077. if (this._forcedOutputTexture) {
  55078. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55079. }
  55080. return this._texelSize;
  55081. },
  55082. enumerable: true,
  55083. configurable: true
  55084. });
  55085. PostProcess.prototype.getEngine = function () {
  55086. return this._engine;
  55087. };
  55088. PostProcess.prototype.getEffect = function () {
  55089. return this._effect;
  55090. };
  55091. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55092. this._disposeTextures();
  55093. this._shareOutputWithPostProcess = postProcess;
  55094. return this;
  55095. };
  55096. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55097. if (defines === void 0) { defines = null; }
  55098. if (uniforms === void 0) { uniforms = null; }
  55099. if (samplers === void 0) { samplers = null; }
  55100. 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);
  55101. };
  55102. PostProcess.prototype.isReusable = function () {
  55103. return this._reusable;
  55104. };
  55105. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55106. PostProcess.prototype.markTextureDirty = function () {
  55107. this.width = -1;
  55108. };
  55109. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55110. var _this = this;
  55111. if (sourceTexture === void 0) { sourceTexture = null; }
  55112. camera = camera || this._camera;
  55113. var scene = camera.getScene();
  55114. var engine = scene.getEngine();
  55115. var maxSize = engine.getCaps().maxTextureSize;
  55116. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55117. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55118. var desiredWidth = (this._options.width || requiredWidth);
  55119. var desiredHeight = this._options.height || requiredHeight;
  55120. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55121. if (this.adaptScaleToCurrentViewport) {
  55122. var currentViewport = engine.currentViewport;
  55123. if (currentViewport) {
  55124. desiredWidth *= currentViewport.width;
  55125. desiredHeight *= currentViewport.height;
  55126. }
  55127. }
  55128. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55129. if (!this._options.width) {
  55130. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55131. }
  55132. if (!this._options.height) {
  55133. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55134. }
  55135. }
  55136. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  55137. if (this._textures.length > 0) {
  55138. for (var i = 0; i < this._textures.length; i++) {
  55139. this._engine._releaseTexture(this._textures.data[i]);
  55140. }
  55141. this._textures.reset();
  55142. }
  55143. this.width = desiredWidth;
  55144. this.height = desiredHeight;
  55145. var textureSize = { width: this.width, height: this.height };
  55146. var textureOptions = {
  55147. generateMipMaps: false,
  55148. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  55149. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  55150. samplingMode: this.renderTargetSamplingMode,
  55151. type: this._textureType
  55152. };
  55153. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55154. if (this._reusable) {
  55155. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55156. }
  55157. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  55158. this.onSizeChangedObservable.notifyObservers(this);
  55159. }
  55160. this._textures.forEach(function (texture) {
  55161. if (texture.samples !== _this.samples) {
  55162. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  55163. }
  55164. });
  55165. }
  55166. var target;
  55167. if (this._shareOutputWithPostProcess) {
  55168. target = this._shareOutputWithPostProcess.outputTexture;
  55169. }
  55170. else if (this._forcedOutputTexture) {
  55171. target = this._forcedOutputTexture;
  55172. this.width = this._forcedOutputTexture.width;
  55173. this.height = this._forcedOutputTexture.height;
  55174. }
  55175. else {
  55176. target = this.outputTexture;
  55177. }
  55178. if (this.enablePixelPerfectMode) {
  55179. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  55180. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  55181. }
  55182. else {
  55183. this._scaleRatio.copyFromFloats(1, 1);
  55184. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  55185. }
  55186. this.onActivateObservable.notifyObservers(camera);
  55187. // Clear
  55188. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  55189. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  55190. }
  55191. if (this._reusable) {
  55192. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  55193. }
  55194. };
  55195. Object.defineProperty(PostProcess.prototype, "isSupported", {
  55196. get: function () {
  55197. return this._effect.isSupported;
  55198. },
  55199. enumerable: true,
  55200. configurable: true
  55201. });
  55202. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  55203. get: function () {
  55204. if (this._shareOutputWithPostProcess) {
  55205. return this._shareOutputWithPostProcess.aspectRatio;
  55206. }
  55207. if (this._forcedOutputTexture) {
  55208. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  55209. }
  55210. return this.width / this.height;
  55211. },
  55212. enumerable: true,
  55213. configurable: true
  55214. });
  55215. /**
  55216. * Get a value indicating if the post-process is ready to be used
  55217. * @returns true if the post-process is ready (shader is compiled)
  55218. */
  55219. PostProcess.prototype.isReady = function () {
  55220. return this._effect && this._effect.isReady();
  55221. };
  55222. PostProcess.prototype.apply = function () {
  55223. // Check
  55224. if (!this._effect || !this._effect.isReady())
  55225. return null;
  55226. // States
  55227. this._engine.enableEffect(this._effect);
  55228. this._engine.setState(false);
  55229. this._engine.setDepthBuffer(false);
  55230. this._engine.setDepthWrite(false);
  55231. // Alpha
  55232. this._engine.setAlphaMode(this.alphaMode);
  55233. if (this.alphaConstants) {
  55234. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  55235. }
  55236. // Texture
  55237. var source;
  55238. if (this._shareOutputWithPostProcess) {
  55239. source = this._shareOutputWithPostProcess.outputTexture;
  55240. }
  55241. else if (this._forcedOutputTexture) {
  55242. source = this._forcedOutputTexture;
  55243. }
  55244. else {
  55245. source = this.outputTexture;
  55246. }
  55247. this._effect._bindTexture("textureSampler", source);
  55248. // Parameters
  55249. this._effect.setVector2("scale", this._scaleRatio);
  55250. this.onApplyObservable.notifyObservers(this._effect);
  55251. return this._effect;
  55252. };
  55253. PostProcess.prototype._disposeTextures = function () {
  55254. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  55255. return;
  55256. }
  55257. if (this._textures.length > 0) {
  55258. for (var i = 0; i < this._textures.length; i++) {
  55259. this._engine._releaseTexture(this._textures.data[i]);
  55260. }
  55261. }
  55262. this._textures.dispose();
  55263. };
  55264. PostProcess.prototype.dispose = function (camera) {
  55265. camera = camera || this._camera;
  55266. this._disposeTextures();
  55267. if (this._scene) {
  55268. var index_1 = this._scene.postProcesses.indexOf(this);
  55269. if (index_1 !== -1) {
  55270. this._scene.postProcesses.splice(index_1, 1);
  55271. }
  55272. }
  55273. else {
  55274. var index_2 = this._engine.postProcesses.indexOf(this);
  55275. if (index_2 !== -1) {
  55276. this._engine.postProcesses.splice(index_2, 1);
  55277. }
  55278. }
  55279. if (!camera) {
  55280. return;
  55281. }
  55282. camera.detachPostProcess(this);
  55283. var index = camera._postProcesses.indexOf(this);
  55284. if (index === 0 && camera._postProcesses.length > 0) {
  55285. this._camera._postProcesses[0].markTextureDirty();
  55286. }
  55287. this.onActivateObservable.clear();
  55288. this.onAfterRenderObservable.clear();
  55289. this.onApplyObservable.clear();
  55290. this.onBeforeRenderObservable.clear();
  55291. this.onSizeChangedObservable.clear();
  55292. };
  55293. return PostProcess;
  55294. }());
  55295. BABYLON.PostProcess = PostProcess;
  55296. })(BABYLON || (BABYLON = {}));
  55297. //# sourceMappingURL=babylon.postProcess.js.map
  55298. var BABYLON;
  55299. (function (BABYLON) {
  55300. var PassPostProcess = /** @class */ (function (_super) {
  55301. __extends(PassPostProcess, _super);
  55302. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55303. if (camera === void 0) { camera = null; }
  55304. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55305. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55306. }
  55307. return PassPostProcess;
  55308. }(BABYLON.PostProcess));
  55309. BABYLON.PassPostProcess = PassPostProcess;
  55310. })(BABYLON || (BABYLON = {}));
  55311. //# sourceMappingURL=babylon.passPostProcess.js.map
  55312. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55313. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55314. s = arguments[i];
  55315. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55316. t[p] = s[p];
  55317. }
  55318. return t;
  55319. };
  55320. var BABYLON;
  55321. (function (BABYLON) {
  55322. var ShadowGenerator = /** @class */ (function () {
  55323. /**
  55324. * Creates a ShadowGenerator object.
  55325. * A ShadowGenerator is the required tool to use the shadows.
  55326. * Each light casting shadows needs to use its own ShadowGenerator.
  55327. * Required parameters :
  55328. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  55329. * - `light`: the light object generating the shadows.
  55330. * - `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.
  55331. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  55332. */
  55333. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  55334. // Members
  55335. this._bias = 0.00005;
  55336. this._blurBoxOffset = 1;
  55337. this._blurScale = 2;
  55338. this._blurKernel = 1;
  55339. this._useKernelBlur = false;
  55340. this._filter = ShadowGenerator.FILTER_NONE;
  55341. this._darkness = 0;
  55342. this._transparencyShadow = false;
  55343. /**
  55344. * Controls the extent to which the shadows fade out at the edge of the frustum
  55345. * Used only by directionals and spots
  55346. */
  55347. this.frustumEdgeFalloff = 0;
  55348. this.forceBackFacesOnly = false;
  55349. this._lightDirection = BABYLON.Vector3.Zero();
  55350. this._viewMatrix = BABYLON.Matrix.Zero();
  55351. this._projectionMatrix = BABYLON.Matrix.Zero();
  55352. this._transformMatrix = BABYLON.Matrix.Zero();
  55353. this._currentFaceIndex = 0;
  55354. this._currentFaceIndexCache = 0;
  55355. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  55356. this._mapSize = mapSize;
  55357. this._light = light;
  55358. this._scene = light.getScene();
  55359. light._shadowGenerator = this;
  55360. // Texture type fallback from float to int if not supported.
  55361. var caps = this._scene.getEngine().getCaps();
  55362. if (!useFullFloatFirst) {
  55363. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55364. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55365. }
  55366. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55367. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55368. }
  55369. else {
  55370. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55371. }
  55372. }
  55373. else {
  55374. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55375. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55376. }
  55377. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55378. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55379. }
  55380. else {
  55381. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55382. }
  55383. }
  55384. this._initializeGenerator();
  55385. }
  55386. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  55387. // Static
  55388. get: function () {
  55389. return ShadowGenerator._FILTER_NONE;
  55390. },
  55391. enumerable: true,
  55392. configurable: true
  55393. });
  55394. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  55395. get: function () {
  55396. return ShadowGenerator._FILTER_POISSONSAMPLING;
  55397. },
  55398. enumerable: true,
  55399. configurable: true
  55400. });
  55401. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  55402. get: function () {
  55403. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  55404. },
  55405. enumerable: true,
  55406. configurable: true
  55407. });
  55408. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  55409. get: function () {
  55410. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  55411. },
  55412. enumerable: true,
  55413. configurable: true
  55414. });
  55415. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  55416. get: function () {
  55417. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55418. },
  55419. enumerable: true,
  55420. configurable: true
  55421. });
  55422. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  55423. get: function () {
  55424. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55425. },
  55426. enumerable: true,
  55427. configurable: true
  55428. });
  55429. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  55430. get: function () {
  55431. return this._bias;
  55432. },
  55433. set: function (bias) {
  55434. this._bias = bias;
  55435. },
  55436. enumerable: true,
  55437. configurable: true
  55438. });
  55439. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55440. get: function () {
  55441. return this._blurBoxOffset;
  55442. },
  55443. set: function (value) {
  55444. if (this._blurBoxOffset === value) {
  55445. return;
  55446. }
  55447. this._blurBoxOffset = value;
  55448. this._disposeBlurPostProcesses();
  55449. },
  55450. enumerable: true,
  55451. configurable: true
  55452. });
  55453. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55454. get: function () {
  55455. return this._blurScale;
  55456. },
  55457. set: function (value) {
  55458. if (this._blurScale === value) {
  55459. return;
  55460. }
  55461. this._blurScale = value;
  55462. this._disposeBlurPostProcesses();
  55463. },
  55464. enumerable: true,
  55465. configurable: true
  55466. });
  55467. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55468. get: function () {
  55469. return this._blurKernel;
  55470. },
  55471. set: function (value) {
  55472. if (this._blurKernel === value) {
  55473. return;
  55474. }
  55475. this._blurKernel = value;
  55476. this._disposeBlurPostProcesses();
  55477. },
  55478. enumerable: true,
  55479. configurable: true
  55480. });
  55481. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55482. get: function () {
  55483. return this._useKernelBlur;
  55484. },
  55485. set: function (value) {
  55486. if (this._useKernelBlur === value) {
  55487. return;
  55488. }
  55489. this._useKernelBlur = value;
  55490. this._disposeBlurPostProcesses();
  55491. },
  55492. enumerable: true,
  55493. configurable: true
  55494. });
  55495. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55496. get: function () {
  55497. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55498. },
  55499. set: function (value) {
  55500. this._depthScale = value;
  55501. },
  55502. enumerable: true,
  55503. configurable: true
  55504. });
  55505. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55506. get: function () {
  55507. return this._filter;
  55508. },
  55509. set: function (value) {
  55510. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55511. if (this._light.needCube()) {
  55512. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55513. this.useExponentialShadowMap = true;
  55514. return;
  55515. }
  55516. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55517. this.useCloseExponentialShadowMap = true;
  55518. return;
  55519. }
  55520. }
  55521. if (this._filter === value) {
  55522. return;
  55523. }
  55524. this._filter = value;
  55525. this._disposeBlurPostProcesses();
  55526. this._applyFilterValues();
  55527. this._light._markMeshesAsLightDirty();
  55528. },
  55529. enumerable: true,
  55530. configurable: true
  55531. });
  55532. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55533. get: function () {
  55534. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55535. },
  55536. set: function (value) {
  55537. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55538. return;
  55539. }
  55540. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55541. },
  55542. enumerable: true,
  55543. configurable: true
  55544. });
  55545. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55546. get: function () {
  55547. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55548. return this.useExponentialShadowMap;
  55549. },
  55550. set: function (value) {
  55551. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55552. this.useExponentialShadowMap = value;
  55553. },
  55554. enumerable: true,
  55555. configurable: true
  55556. });
  55557. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55558. get: function () {
  55559. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55560. return this.useBlurExponentialShadowMap;
  55561. },
  55562. set: function (value) {
  55563. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55564. this.useBlurExponentialShadowMap = value;
  55565. },
  55566. enumerable: true,
  55567. configurable: true
  55568. });
  55569. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55570. get: function () {
  55571. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55572. },
  55573. set: function (value) {
  55574. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55575. return;
  55576. }
  55577. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55578. },
  55579. enumerable: true,
  55580. configurable: true
  55581. });
  55582. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55583. get: function () {
  55584. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55585. },
  55586. set: function (value) {
  55587. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55588. return;
  55589. }
  55590. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55591. },
  55592. enumerable: true,
  55593. configurable: true
  55594. });
  55595. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55596. get: function () {
  55597. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55598. },
  55599. set: function (value) {
  55600. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55601. return;
  55602. }
  55603. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55604. },
  55605. enumerable: true,
  55606. configurable: true
  55607. });
  55608. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55609. get: function () {
  55610. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55611. },
  55612. set: function (value) {
  55613. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55614. return;
  55615. }
  55616. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55617. },
  55618. enumerable: true,
  55619. configurable: true
  55620. });
  55621. /**
  55622. * Returns the darkness value (float).
  55623. */
  55624. ShadowGenerator.prototype.getDarkness = function () {
  55625. return this._darkness;
  55626. };
  55627. /**
  55628. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55629. * Returns the ShadowGenerator.
  55630. */
  55631. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55632. if (darkness >= 1.0)
  55633. this._darkness = 1.0;
  55634. else if (darkness <= 0.0)
  55635. this._darkness = 0.0;
  55636. else
  55637. this._darkness = darkness;
  55638. return this;
  55639. };
  55640. /**
  55641. * Sets the ability to have transparent shadow (boolean).
  55642. * Returns the ShadowGenerator.
  55643. */
  55644. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55645. this._transparencyShadow = hasShadow;
  55646. return this;
  55647. };
  55648. /**
  55649. * Returns a RenderTargetTexture object : the shadow map texture.
  55650. */
  55651. ShadowGenerator.prototype.getShadowMap = function () {
  55652. return this._shadowMap;
  55653. };
  55654. /**
  55655. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55656. */
  55657. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55658. if (this._shadowMap2) {
  55659. return this._shadowMap2;
  55660. }
  55661. return this._shadowMap;
  55662. };
  55663. /**
  55664. * Helper function to add a mesh and its descendants to the list of shadow casters
  55665. * @param mesh Mesh to add
  55666. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  55667. */
  55668. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  55669. if (includeDescendants === void 0) { includeDescendants = true; }
  55670. if (!this._shadowMap) {
  55671. return this;
  55672. }
  55673. if (!this._shadowMap.renderList) {
  55674. this._shadowMap.renderList = [];
  55675. }
  55676. this._shadowMap.renderList.push(mesh);
  55677. if (includeDescendants) {
  55678. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  55679. }
  55680. return this;
  55681. var _a;
  55682. };
  55683. /**
  55684. * Helper function to remove a mesh and its descendants from the list of shadow casters
  55685. * @param mesh Mesh to remove
  55686. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  55687. */
  55688. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  55689. if (includeDescendants === void 0) { includeDescendants = true; }
  55690. if (!this._shadowMap || !this._shadowMap.renderList) {
  55691. return this;
  55692. }
  55693. var index = this._shadowMap.renderList.indexOf(mesh);
  55694. if (index !== -1) {
  55695. this._shadowMap.renderList.splice(index, 1);
  55696. }
  55697. if (includeDescendants) {
  55698. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  55699. var child = _a[_i];
  55700. this.removeShadowCaster(child);
  55701. }
  55702. }
  55703. return this;
  55704. };
  55705. /**
  55706. * Returns the associated light object.
  55707. */
  55708. ShadowGenerator.prototype.getLight = function () {
  55709. return this._light;
  55710. };
  55711. ShadowGenerator.prototype._initializeGenerator = function () {
  55712. this._light._markMeshesAsLightDirty();
  55713. this._initializeShadowMap();
  55714. };
  55715. ShadowGenerator.prototype._initializeShadowMap = function () {
  55716. var _this = this;
  55717. // Render target
  55718. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  55719. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55720. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55721. this._shadowMap.anisotropicFilteringLevel = 1;
  55722. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55723. this._shadowMap.renderParticles = false;
  55724. this._shadowMap.ignoreCameraViewport = true;
  55725. // Record Face Index before render.
  55726. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  55727. _this._currentFaceIndex = faceIndex;
  55728. });
  55729. // Custom render function.
  55730. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  55731. // Blur if required afer render.
  55732. this._shadowMap.onAfterUnbindObservable.add(function () {
  55733. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  55734. return;
  55735. }
  55736. var shadowMap = _this.getShadowMapForRendering();
  55737. if (shadowMap) {
  55738. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  55739. }
  55740. });
  55741. // Clear according to the chosen filter.
  55742. this._shadowMap.onClearObservable.add(function (engine) {
  55743. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  55744. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  55745. }
  55746. else {
  55747. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55748. }
  55749. });
  55750. };
  55751. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  55752. var _this = this;
  55753. var engine = this._scene.getEngine();
  55754. var targetSize = this._mapSize / this.blurScale;
  55755. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  55756. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  55757. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55758. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55759. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55760. }
  55761. if (this.useKernelBlur) {
  55762. 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);
  55763. this._kernelBlurXPostprocess.width = targetSize;
  55764. this._kernelBlurXPostprocess.height = targetSize;
  55765. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  55766. effect.setTexture("textureSampler", _this._shadowMap);
  55767. });
  55768. 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);
  55769. this._kernelBlurXPostprocess.autoClear = false;
  55770. this._kernelBlurYPostprocess.autoClear = false;
  55771. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55772. this._kernelBlurXPostprocess.packedFloat = true;
  55773. this._kernelBlurYPostprocess.packedFloat = true;
  55774. }
  55775. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  55776. }
  55777. else {
  55778. 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);
  55779. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  55780. effect.setFloat2("screenSize", targetSize, targetSize);
  55781. effect.setTexture("textureSampler", _this._shadowMap);
  55782. });
  55783. this._boxBlurPostprocess.autoClear = false;
  55784. this._blurPostProcesses = [this._boxBlurPostprocess];
  55785. }
  55786. };
  55787. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55788. var index;
  55789. var engine = this._scene.getEngine();
  55790. if (depthOnlySubMeshes.length) {
  55791. engine.setColorWrite(false);
  55792. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55793. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  55794. }
  55795. engine.setColorWrite(true);
  55796. }
  55797. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55798. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  55799. }
  55800. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55801. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  55802. }
  55803. if (this._transparencyShadow) {
  55804. for (index = 0; index < transparentSubMeshes.length; index++) {
  55805. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  55806. }
  55807. }
  55808. };
  55809. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  55810. var _this = this;
  55811. var mesh = subMesh.getRenderingMesh();
  55812. var scene = this._scene;
  55813. var engine = scene.getEngine();
  55814. var material = subMesh.getMaterial();
  55815. if (!material) {
  55816. return;
  55817. }
  55818. // Culling
  55819. engine.setState(material.backFaceCulling);
  55820. // Managing instances
  55821. var batch = mesh._getInstancesRenderList(subMesh._id);
  55822. if (batch.mustReturn) {
  55823. return;
  55824. }
  55825. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  55826. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  55827. engine.enableEffect(this._effect);
  55828. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  55829. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  55830. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  55831. this._effect.setVector3("lightPosition", this.getLight().position);
  55832. if (scene.activeCamera) {
  55833. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  55834. }
  55835. // Alpha test
  55836. if (material && material.needAlphaTesting()) {
  55837. var alphaTexture = material.getAlphaTestTexture();
  55838. if (alphaTexture) {
  55839. this._effect.setTexture("diffuseSampler", alphaTexture);
  55840. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  55841. }
  55842. }
  55843. // Bones
  55844. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55845. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  55846. }
  55847. if (this.forceBackFacesOnly) {
  55848. engine.setState(true, 0, false, true);
  55849. }
  55850. // Draw
  55851. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55852. if (this.forceBackFacesOnly) {
  55853. engine.setState(true, 0, false, false);
  55854. }
  55855. }
  55856. else {
  55857. // Need to reset refresh rate of the shadowMap
  55858. if (this._shadowMap) {
  55859. this._shadowMap.resetRefreshCounter();
  55860. }
  55861. }
  55862. };
  55863. ShadowGenerator.prototype._applyFilterValues = function () {
  55864. if (!this._shadowMap) {
  55865. return;
  55866. }
  55867. if (this.filter === ShadowGenerator.FILTER_NONE) {
  55868. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  55869. }
  55870. else {
  55871. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55872. }
  55873. };
  55874. /**
  55875. * Force shader compilation including textures ready check
  55876. */
  55877. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  55878. var _this = this;
  55879. var localOptions = __assign({ useInstances: false }, options);
  55880. var shadowMap = this.getShadowMap();
  55881. if (!shadowMap) {
  55882. if (onCompiled) {
  55883. onCompiled(this);
  55884. }
  55885. return;
  55886. }
  55887. var renderList = shadowMap.renderList;
  55888. if (!renderList) {
  55889. if (onCompiled) {
  55890. onCompiled(this);
  55891. }
  55892. return;
  55893. }
  55894. var subMeshes = new Array();
  55895. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  55896. var mesh = renderList_1[_i];
  55897. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  55898. }
  55899. if (subMeshes.length === 0) {
  55900. if (onCompiled) {
  55901. onCompiled(this);
  55902. }
  55903. return;
  55904. }
  55905. var currentIndex = 0;
  55906. var checkReady = function () {
  55907. if (!_this._scene || !_this._scene.getEngine()) {
  55908. return;
  55909. }
  55910. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  55911. currentIndex++;
  55912. if (currentIndex >= subMeshes.length) {
  55913. if (onCompiled) {
  55914. onCompiled(_this);
  55915. }
  55916. return;
  55917. }
  55918. }
  55919. setTimeout(checkReady, 16);
  55920. };
  55921. checkReady();
  55922. };
  55923. /**
  55924. * Boolean : true when the ShadowGenerator is finally computed.
  55925. */
  55926. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  55927. var defines = [];
  55928. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55929. defines.push("#define FLOAT");
  55930. }
  55931. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  55932. defines.push("#define ESM");
  55933. }
  55934. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55935. var mesh = subMesh.getMesh();
  55936. var material = subMesh.getMaterial();
  55937. // Alpha test
  55938. if (material && material.needAlphaTesting()) {
  55939. var alphaTexture = material.getAlphaTestTexture();
  55940. if (alphaTexture) {
  55941. defines.push("#define ALPHATEST");
  55942. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55943. attribs.push(BABYLON.VertexBuffer.UVKind);
  55944. defines.push("#define UV1");
  55945. }
  55946. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55947. if (alphaTexture.coordinatesIndex === 1) {
  55948. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55949. defines.push("#define UV2");
  55950. }
  55951. }
  55952. }
  55953. }
  55954. // Bones
  55955. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55956. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55957. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55958. if (mesh.numBoneInfluencers > 4) {
  55959. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55960. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55961. }
  55962. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55963. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55964. }
  55965. else {
  55966. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55967. }
  55968. // Instances
  55969. if (useInstances) {
  55970. defines.push("#define INSTANCES");
  55971. attribs.push("world0");
  55972. attribs.push("world1");
  55973. attribs.push("world2");
  55974. attribs.push("world3");
  55975. }
  55976. // Get correct effect
  55977. var join = defines.join("\n");
  55978. if (this._cachedDefines !== join) {
  55979. this._cachedDefines = join;
  55980. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  55981. }
  55982. if (!this._effect.isReady()) {
  55983. return false;
  55984. }
  55985. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  55986. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  55987. this._initializeBlurRTTAndPostProcesses();
  55988. }
  55989. }
  55990. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  55991. return false;
  55992. }
  55993. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  55994. return false;
  55995. }
  55996. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  55997. return false;
  55998. }
  55999. return true;
  56000. };
  56001. /**
  56002. * This creates the defines related to the standard BJS materials.
  56003. */
  56004. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  56005. var scene = this._scene;
  56006. var light = this._light;
  56007. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56008. return;
  56009. }
  56010. defines["SHADOW" + lightIndex] = true;
  56011. if (this.usePoissonSampling) {
  56012. defines["SHADOWPCF" + lightIndex] = true;
  56013. }
  56014. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56015. defines["SHADOWESM" + lightIndex] = true;
  56016. }
  56017. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56018. defines["SHADOWCLOSEESM" + lightIndex] = true;
  56019. }
  56020. if (light.needCube()) {
  56021. defines["SHADOWCUBE" + lightIndex] = true;
  56022. }
  56023. };
  56024. /**
  56025. * This binds shadow lights related to the standard BJS materials.
  56026. * It implies the unifroms available on the materials are the standard BJS ones.
  56027. */
  56028. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  56029. var light = this._light;
  56030. var scene = this._scene;
  56031. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56032. return;
  56033. }
  56034. var camera = scene.activeCamera;
  56035. if (!camera) {
  56036. return;
  56037. }
  56038. var shadowMap = this.getShadowMap();
  56039. if (!shadowMap) {
  56040. return;
  56041. }
  56042. if (!light.needCube()) {
  56043. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  56044. }
  56045. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  56046. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  56047. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  56048. };
  56049. // Methods
  56050. /**
  56051. * Returns a Matrix object : the updated transformation matrix.
  56052. */
  56053. ShadowGenerator.prototype.getTransformMatrix = function () {
  56054. var scene = this._scene;
  56055. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  56056. return this._transformMatrix;
  56057. }
  56058. this._currentRenderID = scene.getRenderId();
  56059. this._currentFaceIndexCache = this._currentFaceIndex;
  56060. var lightPosition = this._light.position;
  56061. if (this._light.computeTransformedInformation()) {
  56062. lightPosition = this._light.transformedPosition;
  56063. }
  56064. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  56065. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  56066. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  56067. }
  56068. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  56069. this._cachedPosition = lightPosition.clone();
  56070. this._cachedDirection = this._lightDirection.clone();
  56071. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  56072. var shadowMap = this.getShadowMap();
  56073. if (shadowMap) {
  56074. var renderList = shadowMap.renderList;
  56075. if (renderList) {
  56076. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  56077. }
  56078. }
  56079. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  56080. }
  56081. return this._transformMatrix;
  56082. };
  56083. ShadowGenerator.prototype.recreateShadowMap = function () {
  56084. var shadowMap = this._shadowMap;
  56085. if (!shadowMap) {
  56086. return;
  56087. }
  56088. // Track render list.
  56089. var renderList = shadowMap.renderList;
  56090. // Clean up existing data.
  56091. this._disposeRTTandPostProcesses();
  56092. // Reinitializes.
  56093. this._initializeGenerator();
  56094. // Reaffect the filter to ensure a correct fallback if necessary.
  56095. this.filter = this.filter;
  56096. // Reaffect the filter.
  56097. this._applyFilterValues();
  56098. // Reaffect Render List.
  56099. this._shadowMap.renderList = renderList;
  56100. };
  56101. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  56102. if (this._shadowMap2) {
  56103. this._shadowMap2.dispose();
  56104. this._shadowMap2 = null;
  56105. }
  56106. if (this._boxBlurPostprocess) {
  56107. this._boxBlurPostprocess.dispose();
  56108. this._boxBlurPostprocess = null;
  56109. }
  56110. if (this._kernelBlurXPostprocess) {
  56111. this._kernelBlurXPostprocess.dispose();
  56112. this._kernelBlurXPostprocess = null;
  56113. }
  56114. if (this._kernelBlurYPostprocess) {
  56115. this._kernelBlurYPostprocess.dispose();
  56116. this._kernelBlurYPostprocess = null;
  56117. }
  56118. this._blurPostProcesses = [];
  56119. };
  56120. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  56121. if (this._shadowMap) {
  56122. this._shadowMap.dispose();
  56123. this._shadowMap = null;
  56124. }
  56125. this._disposeBlurPostProcesses();
  56126. };
  56127. /**
  56128. * Disposes the ShadowGenerator.
  56129. * Returns nothing.
  56130. */
  56131. ShadowGenerator.prototype.dispose = function () {
  56132. this._disposeRTTandPostProcesses();
  56133. if (this._light) {
  56134. this._light._shadowGenerator = null;
  56135. this._light._markMeshesAsLightDirty();
  56136. }
  56137. };
  56138. /**
  56139. * Serializes the ShadowGenerator and returns a serializationObject.
  56140. */
  56141. ShadowGenerator.prototype.serialize = function () {
  56142. var serializationObject = {};
  56143. var shadowMap = this.getShadowMap();
  56144. if (!shadowMap) {
  56145. return serializationObject;
  56146. }
  56147. serializationObject.lightId = this._light.id;
  56148. serializationObject.mapSize = shadowMap.getRenderSize();
  56149. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  56150. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  56151. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56152. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56153. serializationObject.usePoissonSampling = this.usePoissonSampling;
  56154. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  56155. serializationObject.depthScale = this.depthScale;
  56156. serializationObject.darkness = this.getDarkness();
  56157. serializationObject.blurBoxOffset = this.blurBoxOffset;
  56158. serializationObject.blurKernel = this.blurKernel;
  56159. serializationObject.blurScale = this.blurScale;
  56160. serializationObject.useKernelBlur = this.useKernelBlur;
  56161. serializationObject.transparencyShadow = this._transparencyShadow;
  56162. serializationObject.renderList = [];
  56163. if (shadowMap.renderList) {
  56164. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  56165. var mesh = shadowMap.renderList[meshIndex];
  56166. serializationObject.renderList.push(mesh.id);
  56167. }
  56168. }
  56169. return serializationObject;
  56170. };
  56171. /**
  56172. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  56173. */
  56174. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  56175. //casting to point light, as light is missing the position attr and typescript complains.
  56176. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  56177. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  56178. var shadowMap = shadowGenerator.getShadowMap();
  56179. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  56180. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  56181. meshes.forEach(function (mesh) {
  56182. if (!shadowMap) {
  56183. return;
  56184. }
  56185. if (!shadowMap.renderList) {
  56186. shadowMap.renderList = [];
  56187. }
  56188. shadowMap.renderList.push(mesh);
  56189. });
  56190. }
  56191. if (parsedShadowGenerator.usePoissonSampling) {
  56192. shadowGenerator.usePoissonSampling = true;
  56193. }
  56194. else if (parsedShadowGenerator.useExponentialShadowMap) {
  56195. shadowGenerator.useExponentialShadowMap = true;
  56196. }
  56197. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  56198. shadowGenerator.useBlurExponentialShadowMap = true;
  56199. }
  56200. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  56201. shadowGenerator.useCloseExponentialShadowMap = true;
  56202. }
  56203. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  56204. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  56205. }
  56206. else if (parsedShadowGenerator.useVarianceShadowMap) {
  56207. shadowGenerator.useExponentialShadowMap = true;
  56208. }
  56209. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  56210. shadowGenerator.useBlurExponentialShadowMap = true;
  56211. }
  56212. if (parsedShadowGenerator.depthScale) {
  56213. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  56214. }
  56215. if (parsedShadowGenerator.blurScale) {
  56216. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  56217. }
  56218. if (parsedShadowGenerator.blurBoxOffset) {
  56219. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  56220. }
  56221. if (parsedShadowGenerator.useKernelBlur) {
  56222. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  56223. }
  56224. if (parsedShadowGenerator.blurKernel) {
  56225. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  56226. }
  56227. if (parsedShadowGenerator.bias !== undefined) {
  56228. shadowGenerator.bias = parsedShadowGenerator.bias;
  56229. }
  56230. if (parsedShadowGenerator.darkness) {
  56231. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  56232. }
  56233. if (parsedShadowGenerator.transparencyShadow) {
  56234. shadowGenerator.setTransparencyShadow(true);
  56235. }
  56236. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  56237. return shadowGenerator;
  56238. };
  56239. ShadowGenerator._FILTER_NONE = 0;
  56240. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  56241. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  56242. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  56243. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  56244. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  56245. return ShadowGenerator;
  56246. }());
  56247. BABYLON.ShadowGenerator = ShadowGenerator;
  56248. })(BABYLON || (BABYLON = {}));
  56249. //# sourceMappingURL=babylon.shadowGenerator.js.map
  56250. var BABYLON;
  56251. (function (BABYLON) {
  56252. var DefaultLoadingScreen = /** @class */ (function () {
  56253. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  56254. if (_loadingText === void 0) { _loadingText = ""; }
  56255. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  56256. var _this = this;
  56257. this._renderingCanvas = _renderingCanvas;
  56258. this._loadingText = _loadingText;
  56259. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  56260. // Resize
  56261. this._resizeLoadingUI = function () {
  56262. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  56263. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  56264. if (!_this._loadingDiv) {
  56265. return;
  56266. }
  56267. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  56268. _this._loadingDiv.style.left = canvasRect.left + "px";
  56269. _this._loadingDiv.style.top = canvasRect.top + "px";
  56270. _this._loadingDiv.style.width = canvasRect.width + "px";
  56271. _this._loadingDiv.style.height = canvasRect.height + "px";
  56272. };
  56273. }
  56274. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  56275. if (this._loadingDiv) {
  56276. // Do not add a loading screen if there is already one
  56277. return;
  56278. }
  56279. this._loadingDiv = document.createElement("div");
  56280. this._loadingDiv.id = "babylonjsLoadingDiv";
  56281. this._loadingDiv.style.opacity = "0";
  56282. this._loadingDiv.style.transition = "opacity 1.5s ease";
  56283. this._loadingDiv.style.pointerEvents = "none";
  56284. // Loading text
  56285. this._loadingTextDiv = document.createElement("div");
  56286. this._loadingTextDiv.style.position = "absolute";
  56287. this._loadingTextDiv.style.left = "0";
  56288. this._loadingTextDiv.style.top = "50%";
  56289. this._loadingTextDiv.style.marginTop = "80px";
  56290. this._loadingTextDiv.style.width = "100%";
  56291. this._loadingTextDiv.style.height = "20px";
  56292. this._loadingTextDiv.style.fontFamily = "Arial";
  56293. this._loadingTextDiv.style.fontSize = "14px";
  56294. this._loadingTextDiv.style.color = "white";
  56295. this._loadingTextDiv.style.textAlign = "center";
  56296. this._loadingTextDiv.innerHTML = "Loading";
  56297. this._loadingDiv.appendChild(this._loadingTextDiv);
  56298. //set the predefined text
  56299. this._loadingTextDiv.innerHTML = this._loadingText;
  56300. // Generating keyframes
  56301. var style = document.createElement('style');
  56302. style.type = 'text/css';
  56303. 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 }";
  56304. style.innerHTML = keyFrames;
  56305. document.getElementsByTagName('head')[0].appendChild(style);
  56306. // Loading img
  56307. var imgBack = new Image();
  56308. 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";
  56309. imgBack.style.position = "absolute";
  56310. imgBack.style.left = "50%";
  56311. imgBack.style.top = "50%";
  56312. imgBack.style.marginLeft = "-60px";
  56313. imgBack.style.marginTop = "-60px";
  56314. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  56315. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  56316. imgBack.style.transformOrigin = "50% 50%";
  56317. imgBack.style.webkitTransformOrigin = "50% 50%";
  56318. this._loadingDiv.appendChild(imgBack);
  56319. this._resizeLoadingUI();
  56320. window.addEventListener("resize", this._resizeLoadingUI);
  56321. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56322. document.body.appendChild(this._loadingDiv);
  56323. this._loadingDiv.style.opacity = "1";
  56324. };
  56325. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  56326. var _this = this;
  56327. if (!this._loadingDiv) {
  56328. return;
  56329. }
  56330. var onTransitionEnd = function () {
  56331. if (!_this._loadingDiv) {
  56332. return;
  56333. }
  56334. document.body.removeChild(_this._loadingDiv);
  56335. window.removeEventListener("resize", _this._resizeLoadingUI);
  56336. _this._loadingDiv = null;
  56337. };
  56338. this._loadingDiv.style.opacity = "0";
  56339. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  56340. };
  56341. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  56342. set: function (text) {
  56343. this._loadingText = text;
  56344. if (this._loadingTextDiv) {
  56345. this._loadingTextDiv.innerHTML = this._loadingText;
  56346. }
  56347. },
  56348. enumerable: true,
  56349. configurable: true
  56350. });
  56351. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  56352. get: function () {
  56353. return this._loadingDivBackgroundColor;
  56354. },
  56355. set: function (color) {
  56356. this._loadingDivBackgroundColor = color;
  56357. if (!this._loadingDiv) {
  56358. return;
  56359. }
  56360. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56361. },
  56362. enumerable: true,
  56363. configurable: true
  56364. });
  56365. return DefaultLoadingScreen;
  56366. }());
  56367. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  56368. })(BABYLON || (BABYLON = {}));
  56369. //# sourceMappingURL=babylon.loadingScreen.js.map
  56370. var BABYLON;
  56371. (function (BABYLON) {
  56372. var SceneLoaderProgressEvent = /** @class */ (function () {
  56373. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  56374. this.lengthComputable = lengthComputable;
  56375. this.loaded = loaded;
  56376. this.total = total;
  56377. }
  56378. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  56379. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  56380. };
  56381. return SceneLoaderProgressEvent;
  56382. }());
  56383. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  56384. var SceneLoader = /** @class */ (function () {
  56385. function SceneLoader() {
  56386. }
  56387. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  56388. get: function () {
  56389. return 0;
  56390. },
  56391. enumerable: true,
  56392. configurable: true
  56393. });
  56394. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  56395. get: function () {
  56396. return 1;
  56397. },
  56398. enumerable: true,
  56399. configurable: true
  56400. });
  56401. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  56402. get: function () {
  56403. return 2;
  56404. },
  56405. enumerable: true,
  56406. configurable: true
  56407. });
  56408. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  56409. get: function () {
  56410. return 3;
  56411. },
  56412. enumerable: true,
  56413. configurable: true
  56414. });
  56415. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  56416. get: function () {
  56417. return SceneLoader._ForceFullSceneLoadingForIncremental;
  56418. },
  56419. set: function (value) {
  56420. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  56421. },
  56422. enumerable: true,
  56423. configurable: true
  56424. });
  56425. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  56426. get: function () {
  56427. return SceneLoader._ShowLoadingScreen;
  56428. },
  56429. set: function (value) {
  56430. SceneLoader._ShowLoadingScreen = value;
  56431. },
  56432. enumerable: true,
  56433. configurable: true
  56434. });
  56435. Object.defineProperty(SceneLoader, "loggingLevel", {
  56436. get: function () {
  56437. return SceneLoader._loggingLevel;
  56438. },
  56439. set: function (value) {
  56440. SceneLoader._loggingLevel = value;
  56441. },
  56442. enumerable: true,
  56443. configurable: true
  56444. });
  56445. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56446. get: function () {
  56447. return SceneLoader._CleanBoneMatrixWeights;
  56448. },
  56449. set: function (value) {
  56450. SceneLoader._CleanBoneMatrixWeights = value;
  56451. },
  56452. enumerable: true,
  56453. configurable: true
  56454. });
  56455. SceneLoader._getDefaultPlugin = function () {
  56456. return SceneLoader._registeredPlugins[".babylon"];
  56457. };
  56458. SceneLoader._getPluginForExtension = function (extension) {
  56459. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56460. if (registeredPlugin) {
  56461. return registeredPlugin;
  56462. }
  56463. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56464. return SceneLoader._getDefaultPlugin();
  56465. };
  56466. SceneLoader._getPluginForDirectLoad = function (data) {
  56467. for (var extension in SceneLoader._registeredPlugins) {
  56468. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56469. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56470. return SceneLoader._registeredPlugins[extension];
  56471. }
  56472. }
  56473. return SceneLoader._getDefaultPlugin();
  56474. };
  56475. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56476. if (sceneFilename.name) {
  56477. sceneFilename = sceneFilename.name;
  56478. }
  56479. var queryStringPosition = sceneFilename.indexOf("?");
  56480. if (queryStringPosition !== -1) {
  56481. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56482. }
  56483. var dotPosition = sceneFilename.lastIndexOf(".");
  56484. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56485. return SceneLoader._getPluginForExtension(extension);
  56486. };
  56487. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56488. SceneLoader._getDirectLoad = function (sceneFilename) {
  56489. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56490. return sceneFilename.substr(5);
  56491. }
  56492. return null;
  56493. };
  56494. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56495. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56496. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56497. var plugin;
  56498. if (registeredPlugin.plugin.createPlugin) {
  56499. plugin = registeredPlugin.plugin.createPlugin();
  56500. }
  56501. else {
  56502. plugin = registeredPlugin.plugin;
  56503. }
  56504. var useArrayBuffer = registeredPlugin.isBinary;
  56505. var database;
  56506. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56507. var dataCallback = function (data, responseURL) {
  56508. if (scene.isDisposed) {
  56509. onError("Scene has been disposed");
  56510. return;
  56511. }
  56512. scene.database = database;
  56513. onSuccess(plugin, data, responseURL);
  56514. };
  56515. var request = null;
  56516. var pluginDisposed = false;
  56517. var onDisposeObservable = plugin.onDisposeObservable;
  56518. if (onDisposeObservable) {
  56519. onDisposeObservable.add(function () {
  56520. pluginDisposed = true;
  56521. if (request) {
  56522. request.abort();
  56523. request = null;
  56524. }
  56525. onDispose();
  56526. });
  56527. }
  56528. var manifestChecked = function () {
  56529. if (pluginDisposed) {
  56530. return;
  56531. }
  56532. var url = rootUrl + sceneFilename;
  56533. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56534. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56535. } : undefined, database, useArrayBuffer, function (request, exception) {
  56536. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56537. });
  56538. };
  56539. if (directLoad) {
  56540. dataCallback(directLoad);
  56541. return plugin;
  56542. }
  56543. if (rootUrl.indexOf("file:") === -1) {
  56544. if (scene.getEngine().enableOfflineSupport) {
  56545. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56546. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56547. }
  56548. else {
  56549. manifestChecked();
  56550. }
  56551. }
  56552. else {
  56553. var fileOrString = sceneFilename;
  56554. if (fileOrString.name) {
  56555. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56556. }
  56557. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56558. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56559. }
  56560. else {
  56561. onError("Unable to find file named " + sceneFilename);
  56562. }
  56563. }
  56564. return plugin;
  56565. };
  56566. // Public functions
  56567. SceneLoader.GetPluginForExtension = function (extension) {
  56568. return SceneLoader._getPluginForExtension(extension).plugin;
  56569. };
  56570. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56571. return !!SceneLoader._registeredPlugins[extension];
  56572. };
  56573. SceneLoader.RegisterPlugin = function (plugin) {
  56574. if (typeof plugin.extensions === "string") {
  56575. var extension = plugin.extensions;
  56576. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56577. plugin: plugin,
  56578. isBinary: false
  56579. };
  56580. }
  56581. else {
  56582. var extensions = plugin.extensions;
  56583. Object.keys(extensions).forEach(function (extension) {
  56584. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56585. plugin: plugin,
  56586. isBinary: extensions[extension].isBinary
  56587. };
  56588. });
  56589. }
  56590. };
  56591. /**
  56592. * Import meshes into a scene
  56593. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56594. * @param rootUrl a string that defines the root url for scene and resources
  56595. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56596. * @param scene the instance of BABYLON.Scene to append to
  56597. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56598. * @param onProgress a callback with a progress event for each file being loaded
  56599. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56600. */
  56601. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56602. if (onSuccess === void 0) { onSuccess = null; }
  56603. if (onProgress === void 0) { onProgress = null; }
  56604. if (onError === void 0) { onError = null; }
  56605. if (pluginExtension === void 0) { pluginExtension = null; }
  56606. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56607. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56608. return null;
  56609. }
  56610. var loadingToken = {};
  56611. scene._addPendingData(loadingToken);
  56612. var disposeHandler = function () {
  56613. scene._removePendingData(loadingToken);
  56614. };
  56615. var errorHandler = function (message, exception) {
  56616. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56617. if (onError) {
  56618. onError(scene, errorMessage, exception);
  56619. }
  56620. else {
  56621. BABYLON.Tools.Error(errorMessage);
  56622. // should the exception be thrown?
  56623. }
  56624. disposeHandler();
  56625. };
  56626. var progressHandler = onProgress ? function (event) {
  56627. try {
  56628. onProgress(event);
  56629. }
  56630. catch (e) {
  56631. errorHandler("Error in onProgress callback", e);
  56632. }
  56633. } : undefined;
  56634. var successHandler = function (meshes, particleSystems, skeletons) {
  56635. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56636. if (onSuccess) {
  56637. try {
  56638. onSuccess(meshes, particleSystems, skeletons);
  56639. }
  56640. catch (e) {
  56641. errorHandler("Error in onSuccess callback", e);
  56642. }
  56643. }
  56644. scene._removePendingData(loadingToken);
  56645. };
  56646. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56647. if (plugin.rewriteRootURL) {
  56648. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56649. }
  56650. if (plugin.importMesh) {
  56651. var syncedPlugin = plugin;
  56652. var meshes = new Array();
  56653. var particleSystems = new Array();
  56654. var skeletons = new Array();
  56655. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56656. return;
  56657. }
  56658. scene.loadingPluginName = plugin.name;
  56659. successHandler(meshes, particleSystems, skeletons);
  56660. }
  56661. else {
  56662. var asyncedPlugin = plugin;
  56663. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56664. scene.loadingPluginName = plugin.name;
  56665. successHandler(meshes, particleSystems, skeletons);
  56666. }, progressHandler, errorHandler);
  56667. }
  56668. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56669. };
  56670. /**
  56671. * Load a scene
  56672. * @param rootUrl a string that defines the root url for scene and resources
  56673. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56674. * @param engine is the instance of BABYLON.Engine to use to create the scene
  56675. * @param onSuccess a callback with the scene when import succeeds
  56676. * @param onProgress a callback with a progress event for each file being loaded
  56677. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56678. */
  56679. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  56680. if (onSuccess === void 0) { onSuccess = null; }
  56681. if (onProgress === void 0) { onProgress = null; }
  56682. if (onError === void 0) { onError = null; }
  56683. if (pluginExtension === void 0) { pluginExtension = null; }
  56684. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  56685. };
  56686. /**
  56687. * Append a scene
  56688. * @param rootUrl a string that defines the root url for scene and resources
  56689. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56690. * @param scene is the instance of BABYLON.Scene to append to
  56691. * @param onSuccess a callback with the scene when import succeeds
  56692. * @param onProgress a callback with a progress event for each file being loaded
  56693. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56694. */
  56695. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56696. if (onSuccess === void 0) { onSuccess = null; }
  56697. if (onProgress === void 0) { onProgress = null; }
  56698. if (onError === void 0) { onError = null; }
  56699. if (pluginExtension === void 0) { pluginExtension = null; }
  56700. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56701. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56702. return null;
  56703. }
  56704. if (SceneLoader.ShowLoadingScreen) {
  56705. scene.getEngine().displayLoadingUI();
  56706. }
  56707. var loadingToken = {};
  56708. scene._addPendingData(loadingToken);
  56709. var disposeHandler = function () {
  56710. scene._removePendingData(loadingToken);
  56711. scene.getEngine().hideLoadingUI();
  56712. };
  56713. var errorHandler = function (message, exception) {
  56714. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56715. if (onError) {
  56716. onError(scene, errorMessage, exception);
  56717. }
  56718. else {
  56719. BABYLON.Tools.Error(errorMessage);
  56720. // should the exception be thrown?
  56721. }
  56722. disposeHandler();
  56723. };
  56724. var progressHandler = onProgress ? function (event) {
  56725. try {
  56726. onProgress(event);
  56727. }
  56728. catch (e) {
  56729. errorHandler("Error in onProgress callback", e);
  56730. }
  56731. } : undefined;
  56732. var successHandler = function () {
  56733. if (onSuccess) {
  56734. try {
  56735. onSuccess(scene);
  56736. }
  56737. catch (e) {
  56738. errorHandler("Error in onSuccess callback", e);
  56739. }
  56740. }
  56741. scene._removePendingData(loadingToken);
  56742. };
  56743. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56744. if (plugin.load) {
  56745. var syncedPlugin = plugin;
  56746. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  56747. return;
  56748. }
  56749. scene.loadingPluginName = plugin.name;
  56750. successHandler();
  56751. }
  56752. else {
  56753. var asyncedPlugin = plugin;
  56754. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  56755. scene.loadingPluginName = plugin.name;
  56756. successHandler();
  56757. }, progressHandler, errorHandler);
  56758. }
  56759. if (SceneLoader.ShowLoadingScreen) {
  56760. scene.executeWhenReady(function () {
  56761. scene.getEngine().hideLoadingUI();
  56762. });
  56763. }
  56764. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56765. };
  56766. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56767. if (onSuccess === void 0) { onSuccess = null; }
  56768. if (onProgress === void 0) { onProgress = null; }
  56769. if (onError === void 0) { onError = null; }
  56770. if (pluginExtension === void 0) { pluginExtension = null; }
  56771. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56772. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56773. return null;
  56774. }
  56775. var loadingToken = {};
  56776. scene._addPendingData(loadingToken);
  56777. var disposeHandler = function () {
  56778. scene._removePendingData(loadingToken);
  56779. };
  56780. var errorHandler = function (message, exception) {
  56781. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56782. if (onError) {
  56783. onError(scene, errorMessage, exception);
  56784. }
  56785. else {
  56786. BABYLON.Tools.Error(errorMessage);
  56787. // should the exception be thrown?
  56788. }
  56789. disposeHandler();
  56790. };
  56791. var progressHandler = onProgress ? function (event) {
  56792. try {
  56793. onProgress(event);
  56794. }
  56795. catch (e) {
  56796. errorHandler("Error in onProgress callback", e);
  56797. }
  56798. } : undefined;
  56799. var successHandler = function (assets) {
  56800. if (onSuccess) {
  56801. try {
  56802. onSuccess(assets);
  56803. }
  56804. catch (e) {
  56805. errorHandler("Error in onSuccess callback", e);
  56806. }
  56807. }
  56808. scene._removePendingData(loadingToken);
  56809. };
  56810. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56811. if (plugin.loadAssets) {
  56812. var syncedPlugin = plugin;
  56813. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  56814. if (!assetContainer) {
  56815. return;
  56816. }
  56817. scene.loadingPluginName = plugin.name;
  56818. successHandler(assetContainer);
  56819. }
  56820. else if (plugin.loadAssetsAsync) {
  56821. var asyncedPlugin = plugin;
  56822. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  56823. if (assetContainer) {
  56824. scene.loadingPluginName = plugin.name;
  56825. successHandler(assetContainer);
  56826. }
  56827. }, progressHandler, errorHandler);
  56828. }
  56829. else {
  56830. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  56831. }
  56832. if (SceneLoader.ShowLoadingScreen) {
  56833. scene.executeWhenReady(function () {
  56834. scene.getEngine().hideLoadingUI();
  56835. });
  56836. }
  56837. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56838. };
  56839. // Flags
  56840. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  56841. SceneLoader._ShowLoadingScreen = true;
  56842. SceneLoader._CleanBoneMatrixWeights = false;
  56843. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  56844. // Members
  56845. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  56846. SceneLoader._registeredPlugins = {};
  56847. return SceneLoader;
  56848. }());
  56849. BABYLON.SceneLoader = SceneLoader;
  56850. ;
  56851. })(BABYLON || (BABYLON = {}));
  56852. //# sourceMappingURL=babylon.sceneLoader.js.map
  56853. var BABYLON;
  56854. (function (BABYLON) {
  56855. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  56856. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56857. var parsedMaterial = parsedData.materials[index];
  56858. if (parsedMaterial.id === id) {
  56859. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56860. }
  56861. }
  56862. return null;
  56863. };
  56864. var isDescendantOf = function (mesh, names, hierarchyIds) {
  56865. for (var i in names) {
  56866. if (mesh.name === names[i]) {
  56867. hierarchyIds.push(mesh.id);
  56868. return true;
  56869. }
  56870. }
  56871. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  56872. hierarchyIds.push(mesh.id);
  56873. return true;
  56874. }
  56875. return false;
  56876. };
  56877. var logOperation = function (operation, producer) {
  56878. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  56879. };
  56880. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  56881. if (addToScene === void 0) { addToScene = false; }
  56882. var container = new BABYLON.AssetContainer(scene);
  56883. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56884. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56885. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56886. // and avoid problems with multiple concurrent .babylon loads.
  56887. var log = "importScene has failed JSON parse";
  56888. try {
  56889. var parsedData = JSON.parse(data);
  56890. log = "";
  56891. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56892. var index;
  56893. var cache;
  56894. // Lights
  56895. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  56896. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  56897. var parsedLight = parsedData.lights[index];
  56898. var light = BABYLON.Light.Parse(parsedLight, scene);
  56899. if (light) {
  56900. container.lights.push(light);
  56901. log += (index === 0 ? "\n\tLights:" : "");
  56902. log += "\n\t\t" + light.toString(fullDetails);
  56903. }
  56904. }
  56905. }
  56906. // Animations
  56907. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  56908. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  56909. var parsedAnimation = parsedData.animations[index];
  56910. var animation = BABYLON.Animation.Parse(parsedAnimation);
  56911. scene.animations.push(animation);
  56912. container.animations.push(animation);
  56913. log += (index === 0 ? "\n\tAnimations:" : "");
  56914. log += "\n\t\t" + animation.toString(fullDetails);
  56915. }
  56916. }
  56917. // Materials
  56918. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  56919. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56920. var parsedMaterial = parsedData.materials[index];
  56921. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56922. container.materials.push(mat);
  56923. log += (index === 0 ? "\n\tMaterials:" : "");
  56924. log += "\n\t\t" + mat.toString(fullDetails);
  56925. }
  56926. }
  56927. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  56928. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  56929. var parsedMultiMaterial = parsedData.multiMaterials[index];
  56930. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  56931. container.multiMaterials.push(mmat);
  56932. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  56933. log += "\n\t\t" + mmat.toString(fullDetails);
  56934. }
  56935. }
  56936. // Morph targets
  56937. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  56938. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  56939. var managerData = _a[_i];
  56940. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  56941. }
  56942. }
  56943. // Skeletons
  56944. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  56945. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  56946. var parsedSkeleton = parsedData.skeletons[index];
  56947. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  56948. container.skeletons.push(skeleton);
  56949. log += (index === 0 ? "\n\tSkeletons:" : "");
  56950. log += "\n\t\t" + skeleton.toString(fullDetails);
  56951. }
  56952. }
  56953. // Geometries
  56954. var geometries = parsedData.geometries;
  56955. if (geometries !== undefined && geometries !== null) {
  56956. var addedGeometry = new Array();
  56957. // Boxes
  56958. var boxes = geometries.boxes;
  56959. if (boxes !== undefined && boxes !== null) {
  56960. for (index = 0, cache = boxes.length; index < cache; index++) {
  56961. var parsedBox = boxes[index];
  56962. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  56963. }
  56964. }
  56965. // Spheres
  56966. var spheres = geometries.spheres;
  56967. if (spheres !== undefined && spheres !== null) {
  56968. for (index = 0, cache = spheres.length; index < cache; index++) {
  56969. var parsedSphere = spheres[index];
  56970. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  56971. }
  56972. }
  56973. // Cylinders
  56974. var cylinders = geometries.cylinders;
  56975. if (cylinders !== undefined && cylinders !== null) {
  56976. for (index = 0, cache = cylinders.length; index < cache; index++) {
  56977. var parsedCylinder = cylinders[index];
  56978. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  56979. }
  56980. }
  56981. // Toruses
  56982. var toruses = geometries.toruses;
  56983. if (toruses !== undefined && toruses !== null) {
  56984. for (index = 0, cache = toruses.length; index < cache; index++) {
  56985. var parsedTorus = toruses[index];
  56986. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  56987. }
  56988. }
  56989. // Grounds
  56990. var grounds = geometries.grounds;
  56991. if (grounds !== undefined && grounds !== null) {
  56992. for (index = 0, cache = grounds.length; index < cache; index++) {
  56993. var parsedGround = grounds[index];
  56994. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  56995. }
  56996. }
  56997. // Planes
  56998. var planes = geometries.planes;
  56999. if (planes !== undefined && planes !== null) {
  57000. for (index = 0, cache = planes.length; index < cache; index++) {
  57001. var parsedPlane = planes[index];
  57002. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  57003. }
  57004. }
  57005. // TorusKnots
  57006. var torusKnots = geometries.torusKnots;
  57007. if (torusKnots !== undefined && torusKnots !== null) {
  57008. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  57009. var parsedTorusKnot = torusKnots[index];
  57010. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  57011. }
  57012. }
  57013. // VertexData
  57014. var vertexData = geometries.vertexData;
  57015. if (vertexData !== undefined && vertexData !== null) {
  57016. for (index = 0, cache = vertexData.length; index < cache; index++) {
  57017. var parsedVertexData = vertexData[index];
  57018. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  57019. }
  57020. }
  57021. addedGeometry.forEach(function (g) {
  57022. if (g) {
  57023. container.geometries.push(g);
  57024. }
  57025. });
  57026. }
  57027. // Transform nodes
  57028. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  57029. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  57030. var parsedTransformNode = parsedData.transformNodes[index];
  57031. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  57032. container.transformNodes.push(node);
  57033. }
  57034. }
  57035. // Meshes
  57036. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57037. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57038. var parsedMesh = parsedData.meshes[index];
  57039. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57040. container.meshes.push(mesh);
  57041. log += (index === 0 ? "\n\tMeshes:" : "");
  57042. log += "\n\t\t" + mesh.toString(fullDetails);
  57043. }
  57044. }
  57045. // Cameras
  57046. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  57047. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  57048. var parsedCamera = parsedData.cameras[index];
  57049. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  57050. container.cameras.push(camera);
  57051. log += (index === 0 ? "\n\tCameras:" : "");
  57052. log += "\n\t\t" + camera.toString(fullDetails);
  57053. }
  57054. }
  57055. // Browsing all the graph to connect the dots
  57056. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  57057. var camera = scene.cameras[index];
  57058. if (camera._waitingParentId) {
  57059. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  57060. camera._waitingParentId = null;
  57061. }
  57062. }
  57063. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57064. var light_1 = scene.lights[index];
  57065. if (light_1 && light_1._waitingParentId) {
  57066. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  57067. light_1._waitingParentId = null;
  57068. }
  57069. }
  57070. // Sounds
  57071. // TODO: add sound
  57072. var loadedSounds = [];
  57073. var loadedSound;
  57074. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  57075. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  57076. var parsedSound = parsedData.sounds[index];
  57077. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57078. if (!parsedSound.url)
  57079. parsedSound.url = parsedSound.name;
  57080. if (!loadedSounds[parsedSound.url]) {
  57081. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  57082. loadedSounds[parsedSound.url] = loadedSound;
  57083. container.sounds.push(loadedSound);
  57084. }
  57085. else {
  57086. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  57087. }
  57088. }
  57089. else {
  57090. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  57091. }
  57092. }
  57093. }
  57094. loadedSounds = [];
  57095. // Connect parents & children and parse actions
  57096. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  57097. var transformNode = scene.transformNodes[index];
  57098. if (transformNode._waitingParentId) {
  57099. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  57100. transformNode._waitingParentId = null;
  57101. }
  57102. }
  57103. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57104. var mesh = scene.meshes[index];
  57105. if (mesh._waitingParentId) {
  57106. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  57107. mesh._waitingParentId = null;
  57108. }
  57109. if (mesh._waitingActions) {
  57110. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  57111. mesh._waitingActions = null;
  57112. }
  57113. }
  57114. // freeze world matrix application
  57115. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57116. var currentMesh = scene.meshes[index];
  57117. if (currentMesh._waitingFreezeWorldMatrix) {
  57118. currentMesh.freezeWorldMatrix();
  57119. currentMesh._waitingFreezeWorldMatrix = null;
  57120. }
  57121. else {
  57122. currentMesh.computeWorldMatrix(true);
  57123. }
  57124. }
  57125. // Particles Systems
  57126. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57127. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57128. var parsedParticleSystem = parsedData.particleSystems[index];
  57129. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57130. container.particleSystems.push(ps);
  57131. }
  57132. }
  57133. // Lens flares
  57134. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  57135. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  57136. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  57137. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  57138. container.lensFlareSystems.push(lf);
  57139. }
  57140. }
  57141. // Shadows
  57142. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  57143. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  57144. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  57145. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  57146. container.shadowGenerators.push(sg);
  57147. }
  57148. }
  57149. // Lights exclusions / inclusions
  57150. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57151. var light_2 = scene.lights[index];
  57152. // Excluded check
  57153. if (light_2._excludedMeshesIds.length > 0) {
  57154. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  57155. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  57156. if (excludedMesh) {
  57157. light_2.excludedMeshes.push(excludedMesh);
  57158. }
  57159. }
  57160. light_2._excludedMeshesIds = [];
  57161. }
  57162. // Included check
  57163. if (light_2._includedOnlyMeshesIds.length > 0) {
  57164. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  57165. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  57166. if (includedOnlyMesh) {
  57167. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  57168. }
  57169. }
  57170. light_2._includedOnlyMeshesIds = [];
  57171. }
  57172. }
  57173. // Actions (scene)
  57174. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  57175. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  57176. }
  57177. if (!addToScene) {
  57178. container.removeAllFromScene();
  57179. }
  57180. return container;
  57181. }
  57182. catch (err) {
  57183. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  57184. if (onError) {
  57185. onError(msg, err);
  57186. }
  57187. else {
  57188. BABYLON.Tools.Log(msg);
  57189. throw err;
  57190. }
  57191. }
  57192. finally {
  57193. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57194. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57195. }
  57196. }
  57197. return null;
  57198. };
  57199. BABYLON.SceneLoader.RegisterPlugin({
  57200. name: "babylon.js",
  57201. extensions: ".babylon",
  57202. canDirectLoad: function (data) {
  57203. if (data.indexOf("babylon") !== -1) {
  57204. return true;
  57205. }
  57206. return false;
  57207. },
  57208. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  57209. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57210. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57211. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57212. // and avoid problems with multiple concurrent .babylon loads.
  57213. var log = "importMesh has failed JSON parse";
  57214. try {
  57215. var parsedData = JSON.parse(data);
  57216. log = "";
  57217. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57218. if (!meshesNames) {
  57219. meshesNames = null;
  57220. }
  57221. else if (!Array.isArray(meshesNames)) {
  57222. meshesNames = [meshesNames];
  57223. }
  57224. var hierarchyIds = new Array();
  57225. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57226. var loadedSkeletonsIds = [];
  57227. var loadedMaterialsIds = [];
  57228. var index;
  57229. var cache;
  57230. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57231. var parsedMesh = parsedData.meshes[index];
  57232. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  57233. if (meshesNames !== null) {
  57234. // Remove found mesh name from list.
  57235. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  57236. }
  57237. //Geometry?
  57238. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  57239. //does the file contain geometries?
  57240. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  57241. //find the correct geometry and add it to the scene
  57242. var found = false;
  57243. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  57244. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  57245. return;
  57246. }
  57247. else {
  57248. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  57249. if (parsedGeometryData.id === parsedMesh.geometryId) {
  57250. switch (geometryType) {
  57251. case "boxes":
  57252. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  57253. break;
  57254. case "spheres":
  57255. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  57256. break;
  57257. case "cylinders":
  57258. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  57259. break;
  57260. case "toruses":
  57261. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  57262. break;
  57263. case "grounds":
  57264. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  57265. break;
  57266. case "planes":
  57267. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  57268. break;
  57269. case "torusKnots":
  57270. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  57271. break;
  57272. case "vertexData":
  57273. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  57274. break;
  57275. }
  57276. found = true;
  57277. }
  57278. });
  57279. }
  57280. });
  57281. if (found === false) {
  57282. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  57283. }
  57284. }
  57285. }
  57286. // Material ?
  57287. if (parsedMesh.materialId) {
  57288. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  57289. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57290. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  57291. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  57292. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  57293. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  57294. var subMatId = parsedMultiMaterial.materials[matIndex];
  57295. loadedMaterialsIds.push(subMatId);
  57296. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  57297. log += "\n\tMaterial " + mat.toString(fullDetails);
  57298. }
  57299. loadedMaterialsIds.push(parsedMultiMaterial.id);
  57300. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57301. materialFound = true;
  57302. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  57303. break;
  57304. }
  57305. }
  57306. }
  57307. if (materialFound === false) {
  57308. loadedMaterialsIds.push(parsedMesh.materialId);
  57309. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  57310. if (!mat) {
  57311. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  57312. }
  57313. else {
  57314. log += "\n\tMaterial " + mat.toString(fullDetails);
  57315. }
  57316. }
  57317. }
  57318. // Skeleton ?
  57319. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57320. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  57321. if (skeletonAlreadyLoaded === false) {
  57322. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  57323. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  57324. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  57325. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57326. skeletons.push(skeleton);
  57327. loadedSkeletonsIds.push(parsedSkeleton.id);
  57328. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  57329. }
  57330. }
  57331. }
  57332. }
  57333. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57334. meshes.push(mesh);
  57335. log += "\n\tMesh " + mesh.toString(fullDetails);
  57336. }
  57337. }
  57338. // Connecting parents
  57339. var currentMesh;
  57340. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57341. currentMesh = scene.meshes[index];
  57342. if (currentMesh._waitingParentId) {
  57343. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  57344. currentMesh._waitingParentId = null;
  57345. }
  57346. }
  57347. // freeze and compute world matrix application
  57348. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57349. currentMesh = scene.meshes[index];
  57350. if (currentMesh._waitingFreezeWorldMatrix) {
  57351. currentMesh.freezeWorldMatrix();
  57352. currentMesh._waitingFreezeWorldMatrix = null;
  57353. }
  57354. else {
  57355. currentMesh.computeWorldMatrix(true);
  57356. }
  57357. }
  57358. }
  57359. // Particles
  57360. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57361. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57362. var parsedParticleSystem = parsedData.particleSystems[index];
  57363. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  57364. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  57365. }
  57366. }
  57367. }
  57368. return true;
  57369. }
  57370. catch (err) {
  57371. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  57372. if (onError) {
  57373. onError(msg, err);
  57374. }
  57375. else {
  57376. BABYLON.Tools.Log(msg);
  57377. throw err;
  57378. }
  57379. }
  57380. finally {
  57381. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57382. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57383. }
  57384. }
  57385. return false;
  57386. },
  57387. load: function (scene, data, rootUrl, onError) {
  57388. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57389. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57390. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57391. // and avoid problems with multiple concurrent .babylon loads.
  57392. var log = "importScene has failed JSON parse";
  57393. try {
  57394. var parsedData = JSON.parse(data);
  57395. log = "";
  57396. // Scene
  57397. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  57398. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  57399. }
  57400. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  57401. scene.autoClear = parsedData.autoClear;
  57402. }
  57403. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  57404. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  57405. }
  57406. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  57407. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  57408. }
  57409. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  57410. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  57411. }
  57412. // Fog
  57413. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  57414. scene.fogMode = parsedData.fogMode;
  57415. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  57416. scene.fogStart = parsedData.fogStart;
  57417. scene.fogEnd = parsedData.fogEnd;
  57418. scene.fogDensity = parsedData.fogDensity;
  57419. log += "\tFog mode for scene: ";
  57420. switch (scene.fogMode) {
  57421. // getters not compiling, so using hardcoded
  57422. case 1:
  57423. log += "exp\n";
  57424. break;
  57425. case 2:
  57426. log += "exp2\n";
  57427. break;
  57428. case 3:
  57429. log += "linear\n";
  57430. break;
  57431. }
  57432. }
  57433. //Physics
  57434. if (parsedData.physicsEnabled) {
  57435. var physicsPlugin;
  57436. if (parsedData.physicsEngine === "cannon") {
  57437. physicsPlugin = new BABYLON.CannonJSPlugin();
  57438. }
  57439. else if (parsedData.physicsEngine === "oimo") {
  57440. physicsPlugin = new BABYLON.OimoJSPlugin();
  57441. }
  57442. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57443. //else - default engine, which is currently oimo
  57444. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57445. scene.enablePhysics(physicsGravity, physicsPlugin);
  57446. }
  57447. // Metadata
  57448. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57449. scene.metadata = parsedData.metadata;
  57450. }
  57451. //collisions, if defined. otherwise, default is true
  57452. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57453. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57454. }
  57455. scene.workerCollisions = !!parsedData.workerCollisions;
  57456. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57457. if (!container) {
  57458. return false;
  57459. }
  57460. if (parsedData.autoAnimate) {
  57461. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57462. }
  57463. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57464. scene.setActiveCameraByID(parsedData.activeCameraID);
  57465. }
  57466. // Environment texture
  57467. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57468. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57469. if (parsedData.createDefaultSkybox === true) {
  57470. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57471. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57472. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57473. }
  57474. }
  57475. // Finish
  57476. return true;
  57477. }
  57478. catch (err) {
  57479. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57480. if (onError) {
  57481. onError(msg, err);
  57482. }
  57483. else {
  57484. BABYLON.Tools.Log(msg);
  57485. throw err;
  57486. }
  57487. }
  57488. finally {
  57489. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57490. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57491. }
  57492. }
  57493. return false;
  57494. },
  57495. loadAssets: function (scene, data, rootUrl, onError) {
  57496. var container = loadAssets(scene, data, rootUrl, onerror);
  57497. return container;
  57498. }
  57499. });
  57500. })(BABYLON || (BABYLON = {}));
  57501. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57502. var BABYLON;
  57503. (function (BABYLON) {
  57504. var FilesInput = /** @class */ (function () {
  57505. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57506. this.onProcessFileCallback = function () { return true; };
  57507. this._engine = engine;
  57508. this._currentScene = scene;
  57509. this._sceneLoadedCallback = sceneLoadedCallback;
  57510. this._progressCallback = progressCallback;
  57511. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57512. this._textureLoadingCallback = textureLoadingCallback;
  57513. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57514. this._onReloadCallback = onReloadCallback;
  57515. this._errorCallback = errorCallback;
  57516. }
  57517. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57518. var _this = this;
  57519. if (elementToMonitor) {
  57520. this._elementToMonitor = elementToMonitor;
  57521. this._dragEnterHandler = function (e) { _this.drag(e); };
  57522. this._dragOverHandler = function (e) { _this.drag(e); };
  57523. this._dropHandler = function (e) { _this.drop(e); };
  57524. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57525. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57526. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57527. }
  57528. };
  57529. FilesInput.prototype.dispose = function () {
  57530. if (!this._elementToMonitor) {
  57531. return;
  57532. }
  57533. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57534. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57535. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57536. };
  57537. FilesInput.prototype.renderFunction = function () {
  57538. if (this._additionalRenderLoopLogicCallback) {
  57539. this._additionalRenderLoopLogicCallback();
  57540. }
  57541. if (this._currentScene) {
  57542. if (this._textureLoadingCallback) {
  57543. var remaining = this._currentScene.getWaitingItemsCount();
  57544. if (remaining > 0) {
  57545. this._textureLoadingCallback(remaining);
  57546. }
  57547. }
  57548. this._currentScene.render();
  57549. }
  57550. };
  57551. FilesInput.prototype.drag = function (e) {
  57552. e.stopPropagation();
  57553. e.preventDefault();
  57554. };
  57555. FilesInput.prototype.drop = function (eventDrop) {
  57556. eventDrop.stopPropagation();
  57557. eventDrop.preventDefault();
  57558. this.loadFiles(eventDrop);
  57559. };
  57560. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57561. var _this = this;
  57562. var reader = folder.createReader();
  57563. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57564. reader.readEntries(function (entries) {
  57565. remaining.count += entries.length;
  57566. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57567. var entry = entries_1[_i];
  57568. if (entry.isFile) {
  57569. entry.file(function (file) {
  57570. file.correctName = relativePath + file.name;
  57571. files.push(file);
  57572. if (--remaining.count === 0) {
  57573. callback();
  57574. }
  57575. });
  57576. }
  57577. else if (entry.isDirectory) {
  57578. _this._traverseFolder(entry, files, remaining, callback);
  57579. }
  57580. }
  57581. if (--remaining.count) {
  57582. callback();
  57583. }
  57584. });
  57585. };
  57586. FilesInput.prototype._processFiles = function (files) {
  57587. for (var i = 0; i < files.length; i++) {
  57588. var name = files[i].correctName.toLowerCase();
  57589. var extension = name.split('.').pop();
  57590. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57591. continue;
  57592. }
  57593. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57594. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57595. this._sceneFileToLoad = files[i];
  57596. }
  57597. else {
  57598. FilesInput.FilesToLoad[name] = files[i];
  57599. }
  57600. }
  57601. };
  57602. FilesInput.prototype.loadFiles = function (event) {
  57603. var _this = this;
  57604. if (this._startingProcessingFilesCallback)
  57605. this._startingProcessingFilesCallback();
  57606. // Handling data transfer via drag'n'drop
  57607. if (event && event.dataTransfer && event.dataTransfer.files) {
  57608. this._filesToLoad = event.dataTransfer.files;
  57609. }
  57610. // Handling files from input files
  57611. if (event && event.target && event.target.files) {
  57612. this._filesToLoad = event.target.files;
  57613. }
  57614. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57615. var files_1 = new Array();
  57616. var folders = [];
  57617. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57618. for (var i = 0; i < this._filesToLoad.length; i++) {
  57619. var fileToLoad = this._filesToLoad[i];
  57620. var name_1 = fileToLoad.name.toLowerCase();
  57621. var entry = void 0;
  57622. fileToLoad.correctName = name_1;
  57623. if (items) {
  57624. var item = items[i];
  57625. if (item.getAsEntry) {
  57626. entry = item.getAsEntry();
  57627. }
  57628. else if (item.webkitGetAsEntry) {
  57629. entry = item.webkitGetAsEntry();
  57630. }
  57631. }
  57632. if (!entry) {
  57633. files_1.push(fileToLoad);
  57634. }
  57635. else {
  57636. if (entry.isDirectory) {
  57637. folders.push(entry);
  57638. }
  57639. else {
  57640. files_1.push(fileToLoad);
  57641. }
  57642. }
  57643. }
  57644. if (folders.length === 0) {
  57645. this._processFiles(files_1);
  57646. this._processReload();
  57647. }
  57648. else {
  57649. var remaining = { count: folders.length };
  57650. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57651. var folder = folders_1[_i];
  57652. this._traverseFolder(folder, files_1, remaining, function () {
  57653. _this._processFiles(files_1);
  57654. if (remaining.count === 0) {
  57655. _this._processReload();
  57656. }
  57657. });
  57658. }
  57659. }
  57660. }
  57661. };
  57662. FilesInput.prototype._processReload = function () {
  57663. if (this._onReloadCallback) {
  57664. this._onReloadCallback(this._sceneFileToLoad);
  57665. }
  57666. else {
  57667. this.reload();
  57668. }
  57669. };
  57670. FilesInput.prototype.reload = function () {
  57671. var _this = this;
  57672. // If a scene file has been provided
  57673. if (this._sceneFileToLoad) {
  57674. if (this._currentScene) {
  57675. if (BABYLON.Tools.errorsCount > 0) {
  57676. BABYLON.Tools.ClearLogCache();
  57677. }
  57678. this._engine.stopRenderLoop();
  57679. this._currentScene.dispose();
  57680. }
  57681. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  57682. _this._currentScene = newScene;
  57683. if (_this._sceneLoadedCallback) {
  57684. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  57685. }
  57686. // Wait for textures and shaders to be ready
  57687. _this._currentScene.executeWhenReady(function () {
  57688. _this._engine.runRenderLoop(function () {
  57689. _this.renderFunction();
  57690. });
  57691. });
  57692. }, function (progress) {
  57693. if (_this._progressCallback) {
  57694. _this._progressCallback(progress);
  57695. }
  57696. }, function (scene, message) {
  57697. _this._currentScene = scene;
  57698. if (_this._errorCallback) {
  57699. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  57700. }
  57701. });
  57702. }
  57703. else {
  57704. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  57705. }
  57706. };
  57707. FilesInput.FilesToLoad = {};
  57708. return FilesInput;
  57709. }());
  57710. BABYLON.FilesInput = FilesInput;
  57711. })(BABYLON || (BABYLON = {}));
  57712. //# sourceMappingURL=babylon.filesInput.js.map
  57713. var BABYLON;
  57714. (function (BABYLON) {
  57715. /**
  57716. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57717. * The underlying implementation relies on an associative array to ensure the best performances.
  57718. * The value can be anything including 'null' but except 'undefined'
  57719. */
  57720. var StringDictionary = /** @class */ (function () {
  57721. function StringDictionary() {
  57722. this._count = 0;
  57723. this._data = {};
  57724. }
  57725. /**
  57726. * This will clear this dictionary and copy the content from the 'source' one.
  57727. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57728. * @param source the dictionary to take the content from and copy to this dictionary
  57729. */
  57730. StringDictionary.prototype.copyFrom = function (source) {
  57731. var _this = this;
  57732. this.clear();
  57733. source.forEach(function (t, v) { return _this.add(t, v); });
  57734. };
  57735. /**
  57736. * Get a value based from its key
  57737. * @param key the given key to get the matching value from
  57738. * @return the value if found, otherwise undefined is returned
  57739. */
  57740. StringDictionary.prototype.get = function (key) {
  57741. var val = this._data[key];
  57742. if (val !== undefined) {
  57743. return val;
  57744. }
  57745. return undefined;
  57746. };
  57747. /**
  57748. * Get a value from its key or add it if it doesn't exist.
  57749. * This method will ensure you that a given key/data will be present in the dictionary.
  57750. * @param key the given key to get the matching value from
  57751. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57752. * The factory will only be invoked if there's no data for the given key.
  57753. * @return the value corresponding to the key.
  57754. */
  57755. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57756. var val = this.get(key);
  57757. if (val !== undefined) {
  57758. return val;
  57759. }
  57760. val = factory(key);
  57761. if (val) {
  57762. this.add(key, val);
  57763. }
  57764. return val;
  57765. };
  57766. /**
  57767. * Get a value from its key if present in the dictionary otherwise add it
  57768. * @param key the key to get the value from
  57769. * @param val if there's no such key/value pair in the dictionary add it with this value
  57770. * @return the value corresponding to the key
  57771. */
  57772. StringDictionary.prototype.getOrAdd = function (key, val) {
  57773. var curVal = this.get(key);
  57774. if (curVal !== undefined) {
  57775. return curVal;
  57776. }
  57777. this.add(key, val);
  57778. return val;
  57779. };
  57780. /**
  57781. * Check if there's a given key in the dictionary
  57782. * @param key the key to check for
  57783. * @return true if the key is present, false otherwise
  57784. */
  57785. StringDictionary.prototype.contains = function (key) {
  57786. return this._data[key] !== undefined;
  57787. };
  57788. /**
  57789. * Add a new key and its corresponding value
  57790. * @param key the key to add
  57791. * @param value the value corresponding to the key
  57792. * @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
  57793. */
  57794. StringDictionary.prototype.add = function (key, value) {
  57795. if (this._data[key] !== undefined) {
  57796. return false;
  57797. }
  57798. this._data[key] = value;
  57799. ++this._count;
  57800. return true;
  57801. };
  57802. StringDictionary.prototype.set = function (key, value) {
  57803. if (this._data[key] === undefined) {
  57804. return false;
  57805. }
  57806. this._data[key] = value;
  57807. return true;
  57808. };
  57809. /**
  57810. * Get the element of the given key and remove it from the dictionary
  57811. * @param key
  57812. */
  57813. StringDictionary.prototype.getAndRemove = function (key) {
  57814. var val = this.get(key);
  57815. if (val !== undefined) {
  57816. delete this._data[key];
  57817. --this._count;
  57818. return val;
  57819. }
  57820. return null;
  57821. };
  57822. /**
  57823. * Remove a key/value from the dictionary.
  57824. * @param key the key to remove
  57825. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  57826. */
  57827. StringDictionary.prototype.remove = function (key) {
  57828. if (this.contains(key)) {
  57829. delete this._data[key];
  57830. --this._count;
  57831. return true;
  57832. }
  57833. return false;
  57834. };
  57835. /**
  57836. * Clear the whole content of the dictionary
  57837. */
  57838. StringDictionary.prototype.clear = function () {
  57839. this._data = {};
  57840. this._count = 0;
  57841. };
  57842. Object.defineProperty(StringDictionary.prototype, "count", {
  57843. get: function () {
  57844. return this._count;
  57845. },
  57846. enumerable: true,
  57847. configurable: true
  57848. });
  57849. /**
  57850. * Execute a callback on each key/val of the dictionary.
  57851. * Note that you can remove any element in this dictionary in the callback implementation
  57852. * @param callback the callback to execute on a given key/value pair
  57853. */
  57854. StringDictionary.prototype.forEach = function (callback) {
  57855. for (var cur in this._data) {
  57856. var val = this._data[cur];
  57857. callback(cur, val);
  57858. }
  57859. };
  57860. /**
  57861. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  57862. * If the callback returns null or undefined the method will iterate to the next key/value pair
  57863. * Note that you can remove any element in this dictionary in the callback implementation
  57864. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  57865. */
  57866. StringDictionary.prototype.first = function (callback) {
  57867. for (var cur in this._data) {
  57868. var val = this._data[cur];
  57869. var res = callback(cur, val);
  57870. if (res) {
  57871. return res;
  57872. }
  57873. }
  57874. return null;
  57875. };
  57876. return StringDictionary;
  57877. }());
  57878. BABYLON.StringDictionary = StringDictionary;
  57879. })(BABYLON || (BABYLON = {}));
  57880. //# sourceMappingURL=babylon.stringDictionary.js.map
  57881. var BABYLON;
  57882. (function (BABYLON) {
  57883. var Tags = /** @class */ (function () {
  57884. function Tags() {
  57885. }
  57886. Tags.EnableFor = function (obj) {
  57887. obj._tags = obj._tags || {};
  57888. obj.hasTags = function () {
  57889. return Tags.HasTags(obj);
  57890. };
  57891. obj.addTags = function (tagsString) {
  57892. return Tags.AddTagsTo(obj, tagsString);
  57893. };
  57894. obj.removeTags = function (tagsString) {
  57895. return Tags.RemoveTagsFrom(obj, tagsString);
  57896. };
  57897. obj.matchesTagsQuery = function (tagsQuery) {
  57898. return Tags.MatchesQuery(obj, tagsQuery);
  57899. };
  57900. };
  57901. Tags.DisableFor = function (obj) {
  57902. delete obj._tags;
  57903. delete obj.hasTags;
  57904. delete obj.addTags;
  57905. delete obj.removeTags;
  57906. delete obj.matchesTagsQuery;
  57907. };
  57908. Tags.HasTags = function (obj) {
  57909. if (!obj._tags) {
  57910. return false;
  57911. }
  57912. return !BABYLON.Tools.IsEmpty(obj._tags);
  57913. };
  57914. Tags.GetTags = function (obj, asString) {
  57915. if (asString === void 0) { asString = true; }
  57916. if (!obj._tags) {
  57917. return null;
  57918. }
  57919. if (asString) {
  57920. var tagsArray = [];
  57921. for (var tag in obj._tags) {
  57922. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  57923. tagsArray.push(tag);
  57924. }
  57925. }
  57926. return tagsArray.join(" ");
  57927. }
  57928. else {
  57929. return obj._tags;
  57930. }
  57931. };
  57932. // the tags 'true' and 'false' are reserved and cannot be used as tags
  57933. // a tag cannot start with '||', '&&', and '!'
  57934. // it cannot contain whitespaces
  57935. Tags.AddTagsTo = function (obj, tagsString) {
  57936. if (!tagsString) {
  57937. return;
  57938. }
  57939. if (typeof tagsString !== "string") {
  57940. return;
  57941. }
  57942. var tags = tagsString.split(" ");
  57943. tags.forEach(function (tag, index, array) {
  57944. Tags._AddTagTo(obj, tag);
  57945. });
  57946. };
  57947. Tags._AddTagTo = function (obj, tag) {
  57948. tag = tag.trim();
  57949. if (tag === "" || tag === "true" || tag === "false") {
  57950. return;
  57951. }
  57952. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  57953. return;
  57954. }
  57955. Tags.EnableFor(obj);
  57956. obj._tags[tag] = true;
  57957. };
  57958. Tags.RemoveTagsFrom = function (obj, tagsString) {
  57959. if (!Tags.HasTags(obj)) {
  57960. return;
  57961. }
  57962. var tags = tagsString.split(" ");
  57963. for (var t in tags) {
  57964. Tags._RemoveTagFrom(obj, tags[t]);
  57965. }
  57966. };
  57967. Tags._RemoveTagFrom = function (obj, tag) {
  57968. delete obj._tags[tag];
  57969. };
  57970. Tags.MatchesQuery = function (obj, tagsQuery) {
  57971. if (tagsQuery === undefined) {
  57972. return true;
  57973. }
  57974. if (tagsQuery === "") {
  57975. return Tags.HasTags(obj);
  57976. }
  57977. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  57978. };
  57979. return Tags;
  57980. }());
  57981. BABYLON.Tags = Tags;
  57982. })(BABYLON || (BABYLON = {}));
  57983. //# sourceMappingURL=babylon.tags.js.map
  57984. var BABYLON;
  57985. (function (BABYLON) {
  57986. var AndOrNotEvaluator = /** @class */ (function () {
  57987. function AndOrNotEvaluator() {
  57988. }
  57989. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  57990. if (!query.match(/\([^\(\)]*\)/g)) {
  57991. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  57992. }
  57993. else {
  57994. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  57995. // remove parenthesis
  57996. r = r.slice(1, r.length - 1);
  57997. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  57998. });
  57999. }
  58000. if (query === "true") {
  58001. return true;
  58002. }
  58003. if (query === "false") {
  58004. return false;
  58005. }
  58006. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  58007. };
  58008. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  58009. evaluateCallback = evaluateCallback || (function (r) {
  58010. return r === "true" ? true : false;
  58011. });
  58012. var result;
  58013. var or = parenthesisContent.split("||");
  58014. for (var i in or) {
  58015. if (or.hasOwnProperty(i)) {
  58016. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  58017. var and = ori.split("&&");
  58018. if (and.length > 1) {
  58019. for (var j = 0; j < and.length; ++j) {
  58020. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  58021. if (andj !== "true" && andj !== "false") {
  58022. if (andj[0] === "!") {
  58023. result = !evaluateCallback(andj.substring(1));
  58024. }
  58025. else {
  58026. result = evaluateCallback(andj);
  58027. }
  58028. }
  58029. else {
  58030. result = andj === "true" ? true : false;
  58031. }
  58032. if (!result) {
  58033. ori = "false";
  58034. break;
  58035. }
  58036. }
  58037. }
  58038. if (result || ori === "true") {
  58039. result = true;
  58040. break;
  58041. }
  58042. // result equals false (or undefined)
  58043. if (ori !== "true" && ori !== "false") {
  58044. if (ori[0] === "!") {
  58045. result = !evaluateCallback(ori.substring(1));
  58046. }
  58047. else {
  58048. result = evaluateCallback(ori);
  58049. }
  58050. }
  58051. else {
  58052. result = ori === "true" ? true : false;
  58053. }
  58054. }
  58055. }
  58056. // the whole parenthesis scope is replaced by 'true' or 'false'
  58057. return result ? "true" : "false";
  58058. };
  58059. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  58060. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  58061. // remove whitespaces
  58062. r = r.replace(/[\s]/g, function () { return ""; });
  58063. return r.length % 2 ? "!" : "";
  58064. });
  58065. booleanString = booleanString.trim();
  58066. if (booleanString === "!true") {
  58067. booleanString = "false";
  58068. }
  58069. else if (booleanString === "!false") {
  58070. booleanString = "true";
  58071. }
  58072. return booleanString;
  58073. };
  58074. return AndOrNotEvaluator;
  58075. }());
  58076. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  58077. })(BABYLON || (BABYLON = {}));
  58078. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  58079. var BABYLON;
  58080. (function (BABYLON) {
  58081. var Database = /** @class */ (function () {
  58082. function Database(urlToScene, callbackManifestChecked) {
  58083. // Handling various flavors of prefixed version of IndexedDB
  58084. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  58085. this.callbackManifestChecked = callbackManifestChecked;
  58086. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  58087. this.db = null;
  58088. this._enableSceneOffline = false;
  58089. this._enableTexturesOffline = false;
  58090. this.manifestVersionFound = 0;
  58091. this.mustUpdateRessources = false;
  58092. this.hasReachedQuota = false;
  58093. if (!Database.IDBStorageEnabled) {
  58094. this.callbackManifestChecked(true);
  58095. }
  58096. else {
  58097. this.checkManifestFile();
  58098. }
  58099. }
  58100. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  58101. get: function () {
  58102. return this._enableSceneOffline;
  58103. },
  58104. enumerable: true,
  58105. configurable: true
  58106. });
  58107. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  58108. get: function () {
  58109. return this._enableTexturesOffline;
  58110. },
  58111. enumerable: true,
  58112. configurable: true
  58113. });
  58114. Database.prototype.checkManifestFile = function () {
  58115. var _this = this;
  58116. var noManifestFile = function () {
  58117. _this._enableSceneOffline = false;
  58118. _this._enableTexturesOffline = false;
  58119. _this.callbackManifestChecked(false);
  58120. };
  58121. var timeStampUsed = false;
  58122. var manifestURL = this.currentSceneUrl + ".manifest";
  58123. var xhr = new XMLHttpRequest();
  58124. if (navigator.onLine) {
  58125. // Adding a timestamp to by-pass browsers' cache
  58126. timeStampUsed = true;
  58127. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  58128. }
  58129. xhr.open("GET", manifestURL, true);
  58130. xhr.addEventListener("load", function () {
  58131. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58132. try {
  58133. var manifestFile = JSON.parse(xhr.response);
  58134. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  58135. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  58136. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  58137. _this.manifestVersionFound = manifestFile.version;
  58138. }
  58139. if (_this.callbackManifestChecked) {
  58140. _this.callbackManifestChecked(true);
  58141. }
  58142. }
  58143. catch (ex) {
  58144. noManifestFile();
  58145. }
  58146. }
  58147. else {
  58148. noManifestFile();
  58149. }
  58150. }, false);
  58151. xhr.addEventListener("error", function (event) {
  58152. if (timeStampUsed) {
  58153. timeStampUsed = false;
  58154. // Let's retry without the timeStamp
  58155. // It could fail when coupled with HTML5 Offline API
  58156. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  58157. xhr.open("GET", retryManifestURL, true);
  58158. xhr.send();
  58159. }
  58160. else {
  58161. noManifestFile();
  58162. }
  58163. }, false);
  58164. try {
  58165. xhr.send();
  58166. }
  58167. catch (ex) {
  58168. BABYLON.Tools.Error("Error on XHR send request.");
  58169. this.callbackManifestChecked(false);
  58170. }
  58171. };
  58172. Database.prototype.openAsync = function (successCallback, errorCallback) {
  58173. var _this = this;
  58174. var handleError = function () {
  58175. _this.isSupported = false;
  58176. if (errorCallback)
  58177. errorCallback();
  58178. };
  58179. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  58180. // Your browser doesn't support IndexedDB
  58181. this.isSupported = false;
  58182. if (errorCallback)
  58183. errorCallback();
  58184. }
  58185. else {
  58186. // If the DB hasn't been opened or created yet
  58187. if (!this.db) {
  58188. this.hasReachedQuota = false;
  58189. this.isSupported = true;
  58190. var request = this.idbFactory.open("babylonjs", 1);
  58191. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  58192. request.onerror = function (event) {
  58193. handleError();
  58194. };
  58195. // executes when a version change transaction cannot complete due to other active transactions
  58196. request.onblocked = function (event) {
  58197. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  58198. handleError();
  58199. };
  58200. // DB has been opened successfully
  58201. request.onsuccess = function (event) {
  58202. _this.db = request.result;
  58203. successCallback();
  58204. };
  58205. // Initialization of the DB. Creating Scenes & Textures stores
  58206. request.onupgradeneeded = function (event) {
  58207. _this.db = (event.target).result;
  58208. if (_this.db) {
  58209. try {
  58210. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  58211. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  58212. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  58213. }
  58214. catch (ex) {
  58215. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  58216. handleError();
  58217. }
  58218. }
  58219. };
  58220. }
  58221. else {
  58222. if (successCallback)
  58223. successCallback();
  58224. }
  58225. }
  58226. };
  58227. Database.prototype.loadImageFromDB = function (url, image) {
  58228. var _this = this;
  58229. var completeURL = Database.ReturnFullUrlLocation(url);
  58230. var saveAndLoadImage = function () {
  58231. if (!_this.hasReachedQuota && _this.db !== null) {
  58232. // the texture is not yet in the DB, let's try to save it
  58233. _this._saveImageIntoDBAsync(completeURL, image);
  58234. }
  58235. else {
  58236. image.src = url;
  58237. }
  58238. };
  58239. if (!this.mustUpdateRessources) {
  58240. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  58241. }
  58242. else {
  58243. saveAndLoadImage();
  58244. }
  58245. };
  58246. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  58247. if (this.isSupported && this.db !== null) {
  58248. var texture;
  58249. var transaction = this.db.transaction(["textures"]);
  58250. transaction.onabort = function (event) {
  58251. image.src = url;
  58252. };
  58253. transaction.oncomplete = function (event) {
  58254. var blobTextureURL;
  58255. if (texture) {
  58256. var URL = window.URL || window.webkitURL;
  58257. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  58258. image.onerror = function () {
  58259. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  58260. image.src = url;
  58261. };
  58262. image.src = blobTextureURL;
  58263. }
  58264. else {
  58265. notInDBCallback();
  58266. }
  58267. };
  58268. var getRequest = transaction.objectStore("textures").get(url);
  58269. getRequest.onsuccess = function (event) {
  58270. texture = (event.target).result;
  58271. };
  58272. getRequest.onerror = function (event) {
  58273. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  58274. image.src = url;
  58275. };
  58276. }
  58277. else {
  58278. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58279. image.src = url;
  58280. }
  58281. };
  58282. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  58283. var _this = this;
  58284. if (this.isSupported) {
  58285. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  58286. var generateBlobUrl = function () {
  58287. var blobTextureURL;
  58288. if (blob) {
  58289. var URL = window.URL || window.webkitURL;
  58290. try {
  58291. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  58292. }
  58293. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  58294. catch (ex) {
  58295. blobTextureURL = URL.createObjectURL(blob);
  58296. }
  58297. }
  58298. if (blobTextureURL) {
  58299. image.src = blobTextureURL;
  58300. }
  58301. };
  58302. if (Database.IsUASupportingBlobStorage) {
  58303. var xhr = new XMLHttpRequest(), blob;
  58304. xhr.open("GET", url, true);
  58305. xhr.responseType = "blob";
  58306. xhr.addEventListener("load", function () {
  58307. if (xhr.status === 200 && _this.db) {
  58308. // Blob as response (XHR2)
  58309. blob = xhr.response;
  58310. var transaction = _this.db.transaction(["textures"], "readwrite");
  58311. // the transaction could abort because of a QuotaExceededError error
  58312. transaction.onabort = function (event) {
  58313. try {
  58314. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58315. var srcElement = (event.srcElement || event.target);
  58316. var error = srcElement.error;
  58317. if (error && error.name === "QuotaExceededError") {
  58318. _this.hasReachedQuota = true;
  58319. }
  58320. }
  58321. catch (ex) { }
  58322. generateBlobUrl();
  58323. };
  58324. transaction.oncomplete = function (event) {
  58325. generateBlobUrl();
  58326. };
  58327. var newTexture = { textureUrl: url, data: blob };
  58328. try {
  58329. // Put the blob into the dabase
  58330. var addRequest = transaction.objectStore("textures").put(newTexture);
  58331. addRequest.onsuccess = function (event) {
  58332. };
  58333. addRequest.onerror = function (event) {
  58334. generateBlobUrl();
  58335. };
  58336. }
  58337. catch (ex) {
  58338. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  58339. if (ex.code === 25) {
  58340. Database.IsUASupportingBlobStorage = false;
  58341. }
  58342. image.src = url;
  58343. }
  58344. }
  58345. else {
  58346. image.src = url;
  58347. }
  58348. }, false);
  58349. xhr.addEventListener("error", function (event) {
  58350. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  58351. image.src = url;
  58352. }, false);
  58353. xhr.send();
  58354. }
  58355. else {
  58356. image.src = url;
  58357. }
  58358. }
  58359. else {
  58360. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58361. image.src = url;
  58362. }
  58363. };
  58364. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  58365. var _this = this;
  58366. var updateVersion = function () {
  58367. // the version is not yet in the DB or we need to update it
  58368. _this._saveVersionIntoDBAsync(url, versionLoaded);
  58369. };
  58370. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  58371. };
  58372. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  58373. var _this = this;
  58374. if (this.isSupported && this.db) {
  58375. var version;
  58376. try {
  58377. var transaction = this.db.transaction(["versions"]);
  58378. transaction.oncomplete = function (event) {
  58379. if (version) {
  58380. // If the version in the JSON file is > than the version in DB
  58381. if (_this.manifestVersionFound > version.data) {
  58382. _this.mustUpdateRessources = true;
  58383. updateInDBCallback();
  58384. }
  58385. else {
  58386. callback(version.data);
  58387. }
  58388. }
  58389. else {
  58390. _this.mustUpdateRessources = true;
  58391. updateInDBCallback();
  58392. }
  58393. };
  58394. transaction.onabort = function (event) {
  58395. callback(-1);
  58396. };
  58397. var getRequest = transaction.objectStore("versions").get(url);
  58398. getRequest.onsuccess = function (event) {
  58399. version = (event.target).result;
  58400. };
  58401. getRequest.onerror = function (event) {
  58402. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  58403. callback(-1);
  58404. };
  58405. }
  58406. catch (ex) {
  58407. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  58408. callback(-1);
  58409. }
  58410. }
  58411. else {
  58412. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58413. callback(-1);
  58414. }
  58415. };
  58416. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  58417. var _this = this;
  58418. if (this.isSupported && !this.hasReachedQuota && this.db) {
  58419. try {
  58420. // Open a transaction to the database
  58421. var transaction = this.db.transaction(["versions"], "readwrite");
  58422. // the transaction could abort because of a QuotaExceededError error
  58423. transaction.onabort = function (event) {
  58424. try {
  58425. var error = event.srcElement['error'];
  58426. if (error && error.name === "QuotaExceededError") {
  58427. _this.hasReachedQuota = true;
  58428. }
  58429. }
  58430. catch (ex) { }
  58431. callback(-1);
  58432. };
  58433. transaction.oncomplete = function (event) {
  58434. callback(_this.manifestVersionFound);
  58435. };
  58436. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58437. // Put the scene into the database
  58438. var addRequest = transaction.objectStore("versions").put(newVersion);
  58439. addRequest.onsuccess = function (event) {
  58440. };
  58441. addRequest.onerror = function (event) {
  58442. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58443. };
  58444. }
  58445. catch (ex) {
  58446. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58447. callback(-1);
  58448. }
  58449. }
  58450. else {
  58451. callback(-1);
  58452. }
  58453. };
  58454. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58455. var _this = this;
  58456. var completeUrl = Database.ReturnFullUrlLocation(url);
  58457. var saveAndLoadFile = function () {
  58458. // the scene is not yet in the DB, let's try to save it
  58459. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58460. };
  58461. this._checkVersionFromDB(completeUrl, function (version) {
  58462. if (version !== -1) {
  58463. if (!_this.mustUpdateRessources) {
  58464. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58465. }
  58466. else {
  58467. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58468. }
  58469. }
  58470. else {
  58471. if (errorCallback) {
  58472. errorCallback();
  58473. }
  58474. }
  58475. });
  58476. };
  58477. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58478. if (this.isSupported && this.db) {
  58479. var targetStore;
  58480. if (url.indexOf(".babylon") !== -1) {
  58481. targetStore = "scenes";
  58482. }
  58483. else {
  58484. targetStore = "textures";
  58485. }
  58486. var file;
  58487. var transaction = this.db.transaction([targetStore]);
  58488. transaction.oncomplete = function (event) {
  58489. if (file) {
  58490. callback(file.data);
  58491. }
  58492. else {
  58493. notInDBCallback();
  58494. }
  58495. };
  58496. transaction.onabort = function (event) {
  58497. notInDBCallback();
  58498. };
  58499. var getRequest = transaction.objectStore(targetStore).get(url);
  58500. getRequest.onsuccess = function (event) {
  58501. file = (event.target).result;
  58502. };
  58503. getRequest.onerror = function (event) {
  58504. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58505. notInDBCallback();
  58506. };
  58507. }
  58508. else {
  58509. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58510. callback();
  58511. }
  58512. };
  58513. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58514. var _this = this;
  58515. if (this.isSupported) {
  58516. var targetStore;
  58517. if (url.indexOf(".babylon") !== -1) {
  58518. targetStore = "scenes";
  58519. }
  58520. else {
  58521. targetStore = "textures";
  58522. }
  58523. // Create XHR
  58524. var xhr = new XMLHttpRequest();
  58525. var fileData;
  58526. xhr.open("GET", url, true);
  58527. if (useArrayBuffer) {
  58528. xhr.responseType = "arraybuffer";
  58529. }
  58530. if (progressCallback) {
  58531. xhr.onprogress = progressCallback;
  58532. }
  58533. xhr.addEventListener("load", function () {
  58534. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58535. // Blob as response (XHR2)
  58536. //fileData = xhr.responseText;
  58537. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58538. if (!_this.hasReachedQuota && _this.db) {
  58539. // Open a transaction to the database
  58540. var transaction = _this.db.transaction([targetStore], "readwrite");
  58541. // the transaction could abort because of a QuotaExceededError error
  58542. transaction.onabort = function (event) {
  58543. try {
  58544. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58545. var error = event.srcElement['error'];
  58546. if (error && error.name === "QuotaExceededError") {
  58547. _this.hasReachedQuota = true;
  58548. }
  58549. }
  58550. catch (ex) { }
  58551. callback(fileData);
  58552. };
  58553. transaction.oncomplete = function (event) {
  58554. callback(fileData);
  58555. };
  58556. var newFile;
  58557. if (targetStore === "scenes") {
  58558. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58559. }
  58560. else {
  58561. newFile = { textureUrl: url, data: fileData };
  58562. }
  58563. try {
  58564. // Put the scene into the database
  58565. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58566. addRequest.onsuccess = function (event) {
  58567. };
  58568. addRequest.onerror = function (event) {
  58569. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58570. };
  58571. }
  58572. catch (ex) {
  58573. callback(fileData);
  58574. }
  58575. }
  58576. else {
  58577. callback(fileData);
  58578. }
  58579. }
  58580. else {
  58581. callback();
  58582. }
  58583. }, false);
  58584. xhr.addEventListener("error", function (event) {
  58585. BABYLON.Tools.Error("error on XHR request.");
  58586. callback();
  58587. }, false);
  58588. xhr.send();
  58589. }
  58590. else {
  58591. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58592. callback();
  58593. }
  58594. };
  58595. Database.IsUASupportingBlobStorage = true;
  58596. Database.IDBStorageEnabled = true;
  58597. Database.parseURL = function (url) {
  58598. var a = document.createElement('a');
  58599. a.href = url;
  58600. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58601. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58602. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58603. return absLocation;
  58604. };
  58605. Database.ReturnFullUrlLocation = function (url) {
  58606. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58607. return (Database.parseURL(window.location.href) + url);
  58608. }
  58609. else {
  58610. return url;
  58611. }
  58612. };
  58613. return Database;
  58614. }());
  58615. BABYLON.Database = Database;
  58616. })(BABYLON || (BABYLON = {}));
  58617. //# sourceMappingURL=babylon.database.js.map
  58618. var BABYLON;
  58619. (function (BABYLON) {
  58620. var FresnelParameters = /** @class */ (function () {
  58621. function FresnelParameters() {
  58622. this._isEnabled = true;
  58623. this.leftColor = BABYLON.Color3.White();
  58624. this.rightColor = BABYLON.Color3.Black();
  58625. this.bias = 0;
  58626. this.power = 1;
  58627. }
  58628. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58629. get: function () {
  58630. return this._isEnabled;
  58631. },
  58632. set: function (value) {
  58633. if (this._isEnabled === value) {
  58634. return;
  58635. }
  58636. this._isEnabled = value;
  58637. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  58638. },
  58639. enumerable: true,
  58640. configurable: true
  58641. });
  58642. FresnelParameters.prototype.clone = function () {
  58643. var newFresnelParameters = new FresnelParameters();
  58644. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58645. return newFresnelParameters;
  58646. };
  58647. FresnelParameters.prototype.serialize = function () {
  58648. var serializationObject = {};
  58649. serializationObject.isEnabled = this.isEnabled;
  58650. serializationObject.leftColor = this.leftColor;
  58651. serializationObject.rightColor = this.rightColor;
  58652. serializationObject.bias = this.bias;
  58653. serializationObject.power = this.power;
  58654. return serializationObject;
  58655. };
  58656. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58657. var fresnelParameters = new FresnelParameters();
  58658. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58659. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58660. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58661. fresnelParameters.bias = parsedFresnelParameters.bias;
  58662. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58663. return fresnelParameters;
  58664. };
  58665. return FresnelParameters;
  58666. }());
  58667. BABYLON.FresnelParameters = FresnelParameters;
  58668. })(BABYLON || (BABYLON = {}));
  58669. //# sourceMappingURL=babylon.fresnelParameters.js.map
  58670. var BABYLON;
  58671. (function (BABYLON) {
  58672. var MultiMaterial = /** @class */ (function (_super) {
  58673. __extends(MultiMaterial, _super);
  58674. function MultiMaterial(name, scene) {
  58675. var _this = _super.call(this, name, scene, true) || this;
  58676. scene.multiMaterials.push(_this);
  58677. _this.subMaterials = new Array();
  58678. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  58679. return _this;
  58680. }
  58681. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  58682. get: function () {
  58683. return this._subMaterials;
  58684. },
  58685. set: function (value) {
  58686. this._subMaterials = value;
  58687. this._hookArray(value);
  58688. },
  58689. enumerable: true,
  58690. configurable: true
  58691. });
  58692. MultiMaterial.prototype._hookArray = function (array) {
  58693. var _this = this;
  58694. var oldPush = array.push;
  58695. array.push = function () {
  58696. var items = [];
  58697. for (var _i = 0; _i < arguments.length; _i++) {
  58698. items[_i] = arguments[_i];
  58699. }
  58700. var result = oldPush.apply(array, items);
  58701. _this._markAllSubMeshesAsTexturesDirty();
  58702. return result;
  58703. };
  58704. var oldSplice = array.splice;
  58705. array.splice = function (index, deleteCount) {
  58706. var deleted = oldSplice.apply(array, [index, deleteCount]);
  58707. _this._markAllSubMeshesAsTexturesDirty();
  58708. return deleted;
  58709. };
  58710. };
  58711. // Properties
  58712. MultiMaterial.prototype.getSubMaterial = function (index) {
  58713. if (index < 0 || index >= this.subMaterials.length) {
  58714. return this.getScene().defaultMaterial;
  58715. }
  58716. return this.subMaterials[index];
  58717. };
  58718. MultiMaterial.prototype.getActiveTextures = function () {
  58719. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  58720. if (subMaterial) {
  58721. return subMaterial.getActiveTextures();
  58722. }
  58723. else {
  58724. return [];
  58725. }
  58726. }));
  58727. var _a;
  58728. };
  58729. // Methods
  58730. MultiMaterial.prototype.getClassName = function () {
  58731. return "MultiMaterial";
  58732. };
  58733. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  58734. for (var index = 0; index < this.subMaterials.length; index++) {
  58735. var subMaterial = this.subMaterials[index];
  58736. if (subMaterial) {
  58737. if (subMaterial.storeEffectOnSubMeshes) {
  58738. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  58739. return false;
  58740. }
  58741. continue;
  58742. }
  58743. if (!subMaterial.isReady(mesh)) {
  58744. return false;
  58745. }
  58746. }
  58747. }
  58748. return true;
  58749. };
  58750. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  58751. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  58752. for (var index = 0; index < this.subMaterials.length; index++) {
  58753. var subMaterial = null;
  58754. var current = this.subMaterials[index];
  58755. if (cloneChildren && current) {
  58756. subMaterial = current.clone(name + "-" + current.name);
  58757. }
  58758. else {
  58759. subMaterial = this.subMaterials[index];
  58760. }
  58761. newMultiMaterial.subMaterials.push(subMaterial);
  58762. }
  58763. return newMultiMaterial;
  58764. };
  58765. MultiMaterial.prototype.serialize = function () {
  58766. var serializationObject = {};
  58767. serializationObject.name = this.name;
  58768. serializationObject.id = this.id;
  58769. if (BABYLON.Tags) {
  58770. serializationObject.tags = BABYLON.Tags.GetTags(this);
  58771. }
  58772. serializationObject.materials = [];
  58773. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  58774. var subMat = this.subMaterials[matIndex];
  58775. if (subMat) {
  58776. serializationObject.materials.push(subMat.id);
  58777. }
  58778. else {
  58779. serializationObject.materials.push(null);
  58780. }
  58781. }
  58782. return serializationObject;
  58783. };
  58784. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58785. var scene = this.getScene();
  58786. if (!scene) {
  58787. return;
  58788. }
  58789. var index = scene.multiMaterials.indexOf(this);
  58790. if (index >= 0) {
  58791. scene.multiMaterials.splice(index, 1);
  58792. }
  58793. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58794. };
  58795. return MultiMaterial;
  58796. }(BABYLON.Material));
  58797. BABYLON.MultiMaterial = MultiMaterial;
  58798. })(BABYLON || (BABYLON = {}));
  58799. //# sourceMappingURL=babylon.multiMaterial.js.map
  58800. var BABYLON;
  58801. (function (BABYLON) {
  58802. var FreeCameraTouchInput = /** @class */ (function () {
  58803. function FreeCameraTouchInput() {
  58804. this._offsetX = null;
  58805. this._offsetY = null;
  58806. this._pointerPressed = new Array();
  58807. this.touchAngularSensibility = 200000.0;
  58808. this.touchMoveSensibility = 250.0;
  58809. }
  58810. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  58811. var _this = this;
  58812. var previousPosition = null;
  58813. if (this._pointerInput === undefined) {
  58814. this._onLostFocus = function (evt) {
  58815. _this._offsetX = null;
  58816. _this._offsetY = null;
  58817. };
  58818. this._pointerInput = function (p, s) {
  58819. var evt = p.event;
  58820. if (evt.pointerType === "mouse") {
  58821. return;
  58822. }
  58823. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  58824. if (!noPreventDefault) {
  58825. evt.preventDefault();
  58826. }
  58827. _this._pointerPressed.push(evt.pointerId);
  58828. if (_this._pointerPressed.length !== 1) {
  58829. return;
  58830. }
  58831. previousPosition = {
  58832. x: evt.clientX,
  58833. y: evt.clientY
  58834. };
  58835. }
  58836. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  58837. if (!noPreventDefault) {
  58838. evt.preventDefault();
  58839. }
  58840. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58841. if (index === -1) {
  58842. return;
  58843. }
  58844. _this._pointerPressed.splice(index, 1);
  58845. if (index != 0) {
  58846. return;
  58847. }
  58848. previousPosition = null;
  58849. _this._offsetX = null;
  58850. _this._offsetY = null;
  58851. }
  58852. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  58853. if (!noPreventDefault) {
  58854. evt.preventDefault();
  58855. }
  58856. if (!previousPosition) {
  58857. return;
  58858. }
  58859. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58860. if (index != 0) {
  58861. return;
  58862. }
  58863. _this._offsetX = evt.clientX - previousPosition.x;
  58864. _this._offsetY = -(evt.clientY - previousPosition.y);
  58865. }
  58866. };
  58867. }
  58868. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  58869. if (this._onLostFocus) {
  58870. element.addEventListener("blur", this._onLostFocus);
  58871. }
  58872. };
  58873. FreeCameraTouchInput.prototype.detachControl = function (element) {
  58874. if (this._pointerInput && element) {
  58875. if (this._observer) {
  58876. this.camera.getScene().onPointerObservable.remove(this._observer);
  58877. this._observer = null;
  58878. }
  58879. if (this._onLostFocus) {
  58880. element.removeEventListener("blur", this._onLostFocus);
  58881. this._onLostFocus = null;
  58882. }
  58883. this._pointerPressed = [];
  58884. this._offsetX = null;
  58885. this._offsetY = null;
  58886. }
  58887. };
  58888. FreeCameraTouchInput.prototype.checkInputs = function () {
  58889. if (this._offsetX && this._offsetY) {
  58890. var camera = this.camera;
  58891. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  58892. if (this._pointerPressed.length > 1) {
  58893. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  58894. }
  58895. else {
  58896. var speed = camera._computeLocalCameraSpeed();
  58897. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  58898. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  58899. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  58900. }
  58901. }
  58902. };
  58903. FreeCameraTouchInput.prototype.getClassName = function () {
  58904. return "FreeCameraTouchInput";
  58905. };
  58906. FreeCameraTouchInput.prototype.getSimpleName = function () {
  58907. return "touch";
  58908. };
  58909. __decorate([
  58910. BABYLON.serialize()
  58911. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  58912. __decorate([
  58913. BABYLON.serialize()
  58914. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  58915. return FreeCameraTouchInput;
  58916. }());
  58917. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  58918. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  58919. })(BABYLON || (BABYLON = {}));
  58920. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  58921. var BABYLON;
  58922. (function (BABYLON) {
  58923. // We're mainly based on the logic defined into the FreeCamera code
  58924. var TouchCamera = /** @class */ (function (_super) {
  58925. __extends(TouchCamera, _super);
  58926. //-- end properties for backward compatibility for inputs
  58927. function TouchCamera(name, position, scene) {
  58928. var _this = _super.call(this, name, position, scene) || this;
  58929. _this.inputs.addTouch();
  58930. _this._setupInputs();
  58931. return _this;
  58932. }
  58933. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  58934. //-- Begin properties for backward compatibility for inputs
  58935. get: function () {
  58936. var touch = this.inputs.attached["touch"];
  58937. if (touch)
  58938. return touch.touchAngularSensibility;
  58939. return 0;
  58940. },
  58941. set: function (value) {
  58942. var touch = this.inputs.attached["touch"];
  58943. if (touch)
  58944. touch.touchAngularSensibility = value;
  58945. },
  58946. enumerable: true,
  58947. configurable: true
  58948. });
  58949. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  58950. get: function () {
  58951. var touch = this.inputs.attached["touch"];
  58952. if (touch)
  58953. return touch.touchMoveSensibility;
  58954. return 0;
  58955. },
  58956. set: function (value) {
  58957. var touch = this.inputs.attached["touch"];
  58958. if (touch)
  58959. touch.touchMoveSensibility = value;
  58960. },
  58961. enumerable: true,
  58962. configurable: true
  58963. });
  58964. TouchCamera.prototype.getClassName = function () {
  58965. return "TouchCamera";
  58966. };
  58967. TouchCamera.prototype._setupInputs = function () {
  58968. var mouse = this.inputs.attached["mouse"];
  58969. if (mouse) {
  58970. mouse.touchEnabled = false;
  58971. }
  58972. };
  58973. return TouchCamera;
  58974. }(BABYLON.FreeCamera));
  58975. BABYLON.TouchCamera = TouchCamera;
  58976. })(BABYLON || (BABYLON = {}));
  58977. //# sourceMappingURL=babylon.touchCamera.js.map
  58978. var BABYLON;
  58979. (function (BABYLON) {
  58980. var ProceduralTexture = /** @class */ (function (_super) {
  58981. __extends(ProceduralTexture, _super);
  58982. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  58983. if (fallbackTexture === void 0) { fallbackTexture = null; }
  58984. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58985. if (isCube === void 0) { isCube = false; }
  58986. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58987. _this.isCube = isCube;
  58988. _this.isEnabled = true;
  58989. _this._currentRefreshId = -1;
  58990. _this._refreshRate = 1;
  58991. _this._vertexBuffers = {};
  58992. _this._uniforms = new Array();
  58993. _this._samplers = new Array();
  58994. _this._textures = {};
  58995. _this._floats = {};
  58996. _this._floatsArrays = {};
  58997. _this._colors3 = {};
  58998. _this._colors4 = {};
  58999. _this._vectors2 = {};
  59000. _this._vectors3 = {};
  59001. _this._matrices = {};
  59002. _this._fallbackTextureUsed = false;
  59003. scene._proceduralTextures.push(_this);
  59004. _this._engine = scene.getEngine();
  59005. _this.name = name;
  59006. _this.isRenderTarget = true;
  59007. _this._size = size;
  59008. _this._generateMipMaps = generateMipMaps;
  59009. _this.setFragment(fragment);
  59010. _this._fallbackTexture = fallbackTexture;
  59011. if (isCube) {
  59012. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  59013. _this.setFloat("face", 0);
  59014. }
  59015. else {
  59016. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  59017. }
  59018. // VBO
  59019. var vertices = [];
  59020. vertices.push(1, 1);
  59021. vertices.push(-1, 1);
  59022. vertices.push(-1, -1);
  59023. vertices.push(1, -1);
  59024. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59025. _this._createIndexBuffer();
  59026. return _this;
  59027. }
  59028. ProceduralTexture.prototype._createIndexBuffer = function () {
  59029. var engine = this._engine;
  59030. // Indices
  59031. var indices = [];
  59032. indices.push(0);
  59033. indices.push(1);
  59034. indices.push(2);
  59035. indices.push(0);
  59036. indices.push(2);
  59037. indices.push(3);
  59038. this._indexBuffer = engine.createIndexBuffer(indices);
  59039. };
  59040. ProceduralTexture.prototype._rebuild = function () {
  59041. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59042. if (vb) {
  59043. vb._rebuild();
  59044. }
  59045. this._createIndexBuffer();
  59046. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59047. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59048. }
  59049. };
  59050. ProceduralTexture.prototype.reset = function () {
  59051. if (this._effect === undefined) {
  59052. return;
  59053. }
  59054. var engine = this._engine;
  59055. engine._releaseEffect(this._effect);
  59056. };
  59057. ProceduralTexture.prototype.isReady = function () {
  59058. var _this = this;
  59059. var engine = this._engine;
  59060. var shaders;
  59061. if (!this._fragment) {
  59062. return false;
  59063. }
  59064. if (this._fallbackTextureUsed) {
  59065. return true;
  59066. }
  59067. if (this._fragment.fragmentElement !== undefined) {
  59068. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  59069. }
  59070. else {
  59071. shaders = { vertex: "procedural", fragment: this._fragment };
  59072. }
  59073. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  59074. _this.releaseInternalTexture();
  59075. if (_this._fallbackTexture) {
  59076. _this._texture = _this._fallbackTexture._texture;
  59077. if (_this._texture) {
  59078. _this._texture.incrementReferences();
  59079. }
  59080. }
  59081. _this._fallbackTextureUsed = true;
  59082. });
  59083. return this._effect.isReady();
  59084. };
  59085. ProceduralTexture.prototype.resetRefreshCounter = function () {
  59086. this._currentRefreshId = -1;
  59087. };
  59088. ProceduralTexture.prototype.setFragment = function (fragment) {
  59089. this._fragment = fragment;
  59090. };
  59091. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  59092. get: function () {
  59093. return this._refreshRate;
  59094. },
  59095. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59096. set: function (value) {
  59097. this._refreshRate = value;
  59098. this.resetRefreshCounter();
  59099. },
  59100. enumerable: true,
  59101. configurable: true
  59102. });
  59103. ProceduralTexture.prototype._shouldRender = function () {
  59104. if (!this.isEnabled || !this.isReady() || !this._texture) {
  59105. return false;
  59106. }
  59107. if (this._fallbackTextureUsed) {
  59108. return false;
  59109. }
  59110. if (this._currentRefreshId === -1) {
  59111. this._currentRefreshId = 1;
  59112. return true;
  59113. }
  59114. if (this.refreshRate === this._currentRefreshId) {
  59115. this._currentRefreshId = 1;
  59116. return true;
  59117. }
  59118. this._currentRefreshId++;
  59119. return false;
  59120. };
  59121. ProceduralTexture.prototype.getRenderSize = function () {
  59122. return this._size;
  59123. };
  59124. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  59125. if (this._fallbackTextureUsed) {
  59126. return;
  59127. }
  59128. this.releaseInternalTexture();
  59129. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  59130. };
  59131. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  59132. if (this._uniforms.indexOf(uniformName) === -1) {
  59133. this._uniforms.push(uniformName);
  59134. }
  59135. };
  59136. ProceduralTexture.prototype.setTexture = function (name, texture) {
  59137. if (this._samplers.indexOf(name) === -1) {
  59138. this._samplers.push(name);
  59139. }
  59140. this._textures[name] = texture;
  59141. return this;
  59142. };
  59143. ProceduralTexture.prototype.setFloat = function (name, value) {
  59144. this._checkUniform(name);
  59145. this._floats[name] = value;
  59146. return this;
  59147. };
  59148. ProceduralTexture.prototype.setFloats = function (name, value) {
  59149. this._checkUniform(name);
  59150. this._floatsArrays[name] = value;
  59151. return this;
  59152. };
  59153. ProceduralTexture.prototype.setColor3 = function (name, value) {
  59154. this._checkUniform(name);
  59155. this._colors3[name] = value;
  59156. return this;
  59157. };
  59158. ProceduralTexture.prototype.setColor4 = function (name, value) {
  59159. this._checkUniform(name);
  59160. this._colors4[name] = value;
  59161. return this;
  59162. };
  59163. ProceduralTexture.prototype.setVector2 = function (name, value) {
  59164. this._checkUniform(name);
  59165. this._vectors2[name] = value;
  59166. return this;
  59167. };
  59168. ProceduralTexture.prototype.setVector3 = function (name, value) {
  59169. this._checkUniform(name);
  59170. this._vectors3[name] = value;
  59171. return this;
  59172. };
  59173. ProceduralTexture.prototype.setMatrix = function (name, value) {
  59174. this._checkUniform(name);
  59175. this._matrices[name] = value;
  59176. return this;
  59177. };
  59178. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59179. var scene = this.getScene();
  59180. if (!scene) {
  59181. return;
  59182. }
  59183. var engine = this._engine;
  59184. // Render
  59185. engine.enableEffect(this._effect);
  59186. engine.setState(false);
  59187. // Texture
  59188. for (var name in this._textures) {
  59189. this._effect.setTexture(name, this._textures[name]);
  59190. }
  59191. // Float
  59192. for (name in this._floats) {
  59193. this._effect.setFloat(name, this._floats[name]);
  59194. }
  59195. // Floats
  59196. for (name in this._floatsArrays) {
  59197. this._effect.setArray(name, this._floatsArrays[name]);
  59198. }
  59199. // Color3
  59200. for (name in this._colors3) {
  59201. this._effect.setColor3(name, this._colors3[name]);
  59202. }
  59203. // Color4
  59204. for (name in this._colors4) {
  59205. var color = this._colors4[name];
  59206. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59207. }
  59208. // Vector2
  59209. for (name in this._vectors2) {
  59210. this._effect.setVector2(name, this._vectors2[name]);
  59211. }
  59212. // Vector3
  59213. for (name in this._vectors3) {
  59214. this._effect.setVector3(name, this._vectors3[name]);
  59215. }
  59216. // Matrix
  59217. for (name in this._matrices) {
  59218. this._effect.setMatrix(name, this._matrices[name]);
  59219. }
  59220. if (!this._texture) {
  59221. return;
  59222. }
  59223. if (this.isCube) {
  59224. for (var face = 0; face < 6; face++) {
  59225. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  59226. // VBOs
  59227. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59228. this._effect.setFloat("face", face);
  59229. // Clear
  59230. engine.clear(scene.clearColor, true, true, true);
  59231. // Draw order
  59232. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59233. // Mipmaps
  59234. if (face === 5) {
  59235. engine.generateMipMapsForCubemap(this._texture);
  59236. }
  59237. }
  59238. }
  59239. else {
  59240. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  59241. // VBOs
  59242. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59243. // Clear
  59244. engine.clear(scene.clearColor, true, true, true);
  59245. // Draw order
  59246. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59247. }
  59248. // Unbind
  59249. engine.unBindFramebuffer(this._texture, this.isCube);
  59250. if (this.onGenerated) {
  59251. this.onGenerated();
  59252. }
  59253. };
  59254. ProceduralTexture.prototype.clone = function () {
  59255. var textureSize = this.getSize();
  59256. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  59257. // Base texture
  59258. newTexture.hasAlpha = this.hasAlpha;
  59259. newTexture.level = this.level;
  59260. // RenderTarget Texture
  59261. newTexture.coordinatesMode = this.coordinatesMode;
  59262. return newTexture;
  59263. };
  59264. ProceduralTexture.prototype.dispose = function () {
  59265. var scene = this.getScene();
  59266. if (!scene) {
  59267. return;
  59268. }
  59269. var index = scene._proceduralTextures.indexOf(this);
  59270. if (index >= 0) {
  59271. scene._proceduralTextures.splice(index, 1);
  59272. }
  59273. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59274. if (vertexBuffer) {
  59275. vertexBuffer.dispose();
  59276. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59277. }
  59278. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  59279. this._indexBuffer = null;
  59280. }
  59281. _super.prototype.dispose.call(this);
  59282. };
  59283. return ProceduralTexture;
  59284. }(BABYLON.Texture));
  59285. BABYLON.ProceduralTexture = ProceduralTexture;
  59286. })(BABYLON || (BABYLON = {}));
  59287. //# sourceMappingURL=babylon.proceduralTexture.js.map
  59288. var BABYLON;
  59289. (function (BABYLON) {
  59290. var CustomProceduralTexture = /** @class */ (function (_super) {
  59291. __extends(CustomProceduralTexture, _super);
  59292. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  59293. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  59294. _this._animate = true;
  59295. _this._time = 0;
  59296. _this._texturePath = texturePath;
  59297. //Try to load json
  59298. _this.loadJson(texturePath);
  59299. _this.refreshRate = 1;
  59300. return _this;
  59301. }
  59302. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  59303. var _this = this;
  59304. var noConfigFile = function () {
  59305. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  59306. try {
  59307. _this.setFragment(_this._texturePath);
  59308. }
  59309. catch (ex) {
  59310. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  59311. }
  59312. };
  59313. var configFileUrl = jsonUrl + "/config.json";
  59314. var xhr = new XMLHttpRequest();
  59315. xhr.open("GET", configFileUrl, true);
  59316. xhr.addEventListener("load", function () {
  59317. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59318. try {
  59319. _this._config = JSON.parse(xhr.response);
  59320. _this.updateShaderUniforms();
  59321. _this.updateTextures();
  59322. _this.setFragment(_this._texturePath + "/custom");
  59323. _this._animate = _this._config.animate;
  59324. _this.refreshRate = _this._config.refreshrate;
  59325. }
  59326. catch (ex) {
  59327. noConfigFile();
  59328. }
  59329. }
  59330. else {
  59331. noConfigFile();
  59332. }
  59333. }, false);
  59334. xhr.addEventListener("error", function () {
  59335. noConfigFile();
  59336. }, false);
  59337. try {
  59338. xhr.send();
  59339. }
  59340. catch (ex) {
  59341. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  59342. }
  59343. };
  59344. CustomProceduralTexture.prototype.isReady = function () {
  59345. if (!_super.prototype.isReady.call(this)) {
  59346. return false;
  59347. }
  59348. for (var name in this._textures) {
  59349. var texture = this._textures[name];
  59350. if (!texture.isReady()) {
  59351. return false;
  59352. }
  59353. }
  59354. return true;
  59355. };
  59356. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59357. var scene = this.getScene();
  59358. if (this._animate && scene) {
  59359. this._time += scene.getAnimationRatio() * 0.03;
  59360. this.updateShaderUniforms();
  59361. }
  59362. _super.prototype.render.call(this, useCameraPostProcess);
  59363. };
  59364. CustomProceduralTexture.prototype.updateTextures = function () {
  59365. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  59366. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  59367. }
  59368. };
  59369. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  59370. if (this._config) {
  59371. for (var j = 0; j < this._config.uniforms.length; j++) {
  59372. var uniform = this._config.uniforms[j];
  59373. switch (uniform.type) {
  59374. case "float":
  59375. this.setFloat(uniform.name, uniform.value);
  59376. break;
  59377. case "color3":
  59378. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  59379. break;
  59380. case "color4":
  59381. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  59382. break;
  59383. case "vector2":
  59384. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  59385. break;
  59386. case "vector3":
  59387. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  59388. break;
  59389. }
  59390. }
  59391. }
  59392. this.setFloat("time", this._time);
  59393. };
  59394. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  59395. get: function () {
  59396. return this._animate;
  59397. },
  59398. set: function (value) {
  59399. this._animate = value;
  59400. },
  59401. enumerable: true,
  59402. configurable: true
  59403. });
  59404. return CustomProceduralTexture;
  59405. }(BABYLON.ProceduralTexture));
  59406. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  59407. })(BABYLON || (BABYLON = {}));
  59408. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  59409. var BABYLON;
  59410. (function (BABYLON) {
  59411. var FreeCameraGamepadInput = /** @class */ (function () {
  59412. function FreeCameraGamepadInput() {
  59413. this.gamepadAngularSensibility = 200;
  59414. this.gamepadMoveSensibility = 40;
  59415. // private members
  59416. this._cameraTransform = BABYLON.Matrix.Identity();
  59417. this._deltaTransform = BABYLON.Vector3.Zero();
  59418. this._vector3 = BABYLON.Vector3.Zero();
  59419. this._vector2 = BABYLON.Vector2.Zero();
  59420. }
  59421. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59422. var _this = this;
  59423. var manager = this.camera.getScene().gamepadManager;
  59424. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59425. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59426. // prioritize XBOX gamepads.
  59427. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59428. _this.gamepad = gamepad;
  59429. }
  59430. }
  59431. });
  59432. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59433. if (_this.gamepad === gamepad) {
  59434. _this.gamepad = null;
  59435. }
  59436. });
  59437. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59438. };
  59439. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59440. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59441. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59442. this.gamepad = null;
  59443. };
  59444. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59445. if (this.gamepad && this.gamepad.leftStick) {
  59446. var camera = this.camera;
  59447. var LSValues = this.gamepad.leftStick;
  59448. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59449. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59450. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59451. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59452. var RSValues = this.gamepad.rightStick;
  59453. if (RSValues) {
  59454. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59455. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59456. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59457. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59458. }
  59459. else {
  59460. RSValues = { x: 0, y: 0 };
  59461. }
  59462. if (!camera.rotationQuaternion) {
  59463. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59464. }
  59465. else {
  59466. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59467. }
  59468. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59469. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59470. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59471. camera.cameraDirection.addInPlace(this._deltaTransform);
  59472. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59473. camera.cameraRotation.addInPlace(this._vector2);
  59474. }
  59475. };
  59476. FreeCameraGamepadInput.prototype.getClassName = function () {
  59477. return "FreeCameraGamepadInput";
  59478. };
  59479. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59480. return "gamepad";
  59481. };
  59482. __decorate([
  59483. BABYLON.serialize()
  59484. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59485. __decorate([
  59486. BABYLON.serialize()
  59487. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59488. return FreeCameraGamepadInput;
  59489. }());
  59490. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59491. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59492. })(BABYLON || (BABYLON = {}));
  59493. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59494. var BABYLON;
  59495. (function (BABYLON) {
  59496. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59497. function ArcRotateCameraGamepadInput() {
  59498. this.gamepadRotationSensibility = 80;
  59499. this.gamepadMoveSensibility = 40;
  59500. }
  59501. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59502. var _this = this;
  59503. var manager = this.camera.getScene().gamepadManager;
  59504. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59505. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59506. // prioritize XBOX gamepads.
  59507. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59508. _this.gamepad = gamepad;
  59509. }
  59510. }
  59511. });
  59512. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59513. if (_this.gamepad === gamepad) {
  59514. _this.gamepad = null;
  59515. }
  59516. });
  59517. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59518. };
  59519. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59520. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59521. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59522. this.gamepad = null;
  59523. };
  59524. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59525. if (this.gamepad) {
  59526. var camera = this.camera;
  59527. var RSValues = this.gamepad.rightStick;
  59528. if (RSValues) {
  59529. if (RSValues.x != 0) {
  59530. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59531. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59532. camera.inertialAlphaOffset += normalizedRX;
  59533. }
  59534. }
  59535. if (RSValues.y != 0) {
  59536. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59537. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59538. camera.inertialBetaOffset += normalizedRY;
  59539. }
  59540. }
  59541. }
  59542. var LSValues = this.gamepad.leftStick;
  59543. if (LSValues && LSValues.y != 0) {
  59544. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59545. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59546. this.camera.inertialRadiusOffset -= normalizedLY;
  59547. }
  59548. }
  59549. }
  59550. };
  59551. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59552. return "ArcRotateCameraGamepadInput";
  59553. };
  59554. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59555. return "gamepad";
  59556. };
  59557. __decorate([
  59558. BABYLON.serialize()
  59559. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59560. __decorate([
  59561. BABYLON.serialize()
  59562. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59563. return ArcRotateCameraGamepadInput;
  59564. }());
  59565. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59566. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59567. })(BABYLON || (BABYLON = {}));
  59568. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59569. var BABYLON;
  59570. (function (BABYLON) {
  59571. var GamepadManager = /** @class */ (function () {
  59572. function GamepadManager(_scene) {
  59573. var _this = this;
  59574. this._scene = _scene;
  59575. this._babylonGamepads = [];
  59576. this._oneGamepadConnected = false;
  59577. this._isMonitoring = false;
  59578. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59579. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59580. this._gamepadEventSupported = false;
  59581. }
  59582. else {
  59583. this._gamepadEventSupported = 'GamepadEvent' in window;
  59584. this._gamepadSupport = (navigator.getGamepads ||
  59585. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59586. }
  59587. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59588. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59589. for (var i in _this._babylonGamepads) {
  59590. var gamepad = _this._babylonGamepads[i];
  59591. if (gamepad && gamepad._isConnected) {
  59592. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59593. }
  59594. }
  59595. });
  59596. this._onGamepadConnectedEvent = function (evt) {
  59597. var gamepad = evt.gamepad;
  59598. if (gamepad.index in _this._babylonGamepads) {
  59599. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59600. return;
  59601. }
  59602. }
  59603. var newGamepad;
  59604. if (_this._babylonGamepads[gamepad.index]) {
  59605. newGamepad = _this._babylonGamepads[gamepad.index];
  59606. newGamepad.browserGamepad = gamepad;
  59607. newGamepad._isConnected = true;
  59608. }
  59609. else {
  59610. newGamepad = _this._addNewGamepad(gamepad);
  59611. }
  59612. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59613. _this._startMonitoringGamepads();
  59614. };
  59615. this._onGamepadDisconnectedEvent = function (evt) {
  59616. var gamepad = evt.gamepad;
  59617. // Remove the gamepad from the list of gamepads to monitor.
  59618. for (var i in _this._babylonGamepads) {
  59619. if (_this._babylonGamepads[i].index === gamepad.index) {
  59620. var disconnectedGamepad = _this._babylonGamepads[i];
  59621. disconnectedGamepad._isConnected = false;
  59622. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59623. break;
  59624. }
  59625. }
  59626. };
  59627. if (this._gamepadSupport) {
  59628. //first add already-connected gamepads
  59629. this._updateGamepadObjects();
  59630. if (this._babylonGamepads.length) {
  59631. this._startMonitoringGamepads();
  59632. }
  59633. // Checking if the gamepad connected event is supported (like in Firefox)
  59634. if (this._gamepadEventSupported) {
  59635. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59636. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59637. }
  59638. else {
  59639. this._startMonitoringGamepads();
  59640. }
  59641. }
  59642. }
  59643. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59644. get: function () {
  59645. return this._babylonGamepads;
  59646. },
  59647. enumerable: true,
  59648. configurable: true
  59649. });
  59650. GamepadManager.prototype.getGamepadByType = function (type) {
  59651. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59652. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59653. var gamepad = _a[_i];
  59654. if (gamepad && gamepad.type === type) {
  59655. return gamepad;
  59656. }
  59657. }
  59658. return null;
  59659. };
  59660. GamepadManager.prototype.dispose = function () {
  59661. if (this._gamepadEventSupported) {
  59662. if (this._onGamepadConnectedEvent) {
  59663. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59664. }
  59665. if (this._onGamepadDisconnectedEvent) {
  59666. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  59667. }
  59668. this._onGamepadConnectedEvent = null;
  59669. this._onGamepadDisconnectedEvent = null;
  59670. }
  59671. this._babylonGamepads.forEach(function (gamepad) {
  59672. gamepad.dispose();
  59673. });
  59674. this.onGamepadConnectedObservable.clear();
  59675. this.onGamepadDisconnectedObservable.clear();
  59676. this._oneGamepadConnected = false;
  59677. this._stopMonitoringGamepads();
  59678. this._babylonGamepads = [];
  59679. };
  59680. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  59681. if (!this._oneGamepadConnected) {
  59682. this._oneGamepadConnected = true;
  59683. }
  59684. var newGamepad;
  59685. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  59686. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  59687. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  59688. }
  59689. else if (gamepad.pose) {
  59690. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  59691. }
  59692. else {
  59693. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  59694. }
  59695. this._babylonGamepads[newGamepad.index] = newGamepad;
  59696. return newGamepad;
  59697. };
  59698. GamepadManager.prototype._startMonitoringGamepads = function () {
  59699. if (!this._isMonitoring) {
  59700. this._isMonitoring = true;
  59701. //back-comp
  59702. if (!this._scene) {
  59703. this._checkGamepadsStatus();
  59704. }
  59705. }
  59706. };
  59707. GamepadManager.prototype._stopMonitoringGamepads = function () {
  59708. this._isMonitoring = false;
  59709. };
  59710. GamepadManager.prototype._checkGamepadsStatus = function () {
  59711. var _this = this;
  59712. // Hack to be compatible Chrome
  59713. this._updateGamepadObjects();
  59714. for (var i in this._babylonGamepads) {
  59715. var gamepad = this._babylonGamepads[i];
  59716. if (!gamepad || !gamepad.isConnected) {
  59717. continue;
  59718. }
  59719. gamepad.update();
  59720. }
  59721. if (this._isMonitoring && !this._scene) {
  59722. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  59723. }
  59724. };
  59725. // This function is called only on Chrome, which does not properly support
  59726. // connection/disconnection events and forces you to recopy again the gamepad object
  59727. GamepadManager.prototype._updateGamepadObjects = function () {
  59728. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  59729. for (var i = 0; i < gamepads.length; i++) {
  59730. if (gamepads[i]) {
  59731. if (!this._babylonGamepads[gamepads[i].index]) {
  59732. var newGamepad = this._addNewGamepad(gamepads[i]);
  59733. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59734. }
  59735. else {
  59736. // Forced to copy again this object for Chrome for unknown reason
  59737. this._babylonGamepads[i].browserGamepad = gamepads[i];
  59738. if (!this._babylonGamepads[i].isConnected) {
  59739. this._babylonGamepads[i]._isConnected = true;
  59740. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  59741. }
  59742. }
  59743. }
  59744. }
  59745. };
  59746. return GamepadManager;
  59747. }());
  59748. BABYLON.GamepadManager = GamepadManager;
  59749. })(BABYLON || (BABYLON = {}));
  59750. //# sourceMappingURL=babylon.gamepadManager.js.map
  59751. var BABYLON;
  59752. (function (BABYLON) {
  59753. var StickValues = /** @class */ (function () {
  59754. function StickValues(x, y) {
  59755. this.x = x;
  59756. this.y = y;
  59757. }
  59758. return StickValues;
  59759. }());
  59760. BABYLON.StickValues = StickValues;
  59761. var Gamepad = /** @class */ (function () {
  59762. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  59763. if (leftStickX === void 0) { leftStickX = 0; }
  59764. if (leftStickY === void 0) { leftStickY = 1; }
  59765. if (rightStickX === void 0) { rightStickX = 2; }
  59766. if (rightStickY === void 0) { rightStickY = 3; }
  59767. this.id = id;
  59768. this.index = index;
  59769. this.browserGamepad = browserGamepad;
  59770. this._isConnected = true;
  59771. this._invertLeftStickY = false;
  59772. this.type = Gamepad.GAMEPAD;
  59773. this._leftStickAxisX = leftStickX;
  59774. this._leftStickAxisY = leftStickY;
  59775. this._rightStickAxisX = rightStickX;
  59776. this._rightStickAxisY = rightStickY;
  59777. if (this.browserGamepad.axes.length >= 2) {
  59778. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59779. }
  59780. if (this.browserGamepad.axes.length >= 4) {
  59781. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59782. }
  59783. }
  59784. Object.defineProperty(Gamepad.prototype, "isConnected", {
  59785. get: function () {
  59786. return this._isConnected;
  59787. },
  59788. enumerable: true,
  59789. configurable: true
  59790. });
  59791. Gamepad.prototype.onleftstickchanged = function (callback) {
  59792. this._onleftstickchanged = callback;
  59793. };
  59794. Gamepad.prototype.onrightstickchanged = function (callback) {
  59795. this._onrightstickchanged = callback;
  59796. };
  59797. Object.defineProperty(Gamepad.prototype, "leftStick", {
  59798. get: function () {
  59799. return this._leftStick;
  59800. },
  59801. set: function (newValues) {
  59802. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  59803. this._onleftstickchanged(newValues);
  59804. }
  59805. this._leftStick = newValues;
  59806. },
  59807. enumerable: true,
  59808. configurable: true
  59809. });
  59810. Object.defineProperty(Gamepad.prototype, "rightStick", {
  59811. get: function () {
  59812. return this._rightStick;
  59813. },
  59814. set: function (newValues) {
  59815. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  59816. this._onrightstickchanged(newValues);
  59817. }
  59818. this._rightStick = newValues;
  59819. },
  59820. enumerable: true,
  59821. configurable: true
  59822. });
  59823. Gamepad.prototype.update = function () {
  59824. if (this._leftStick) {
  59825. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59826. if (this._invertLeftStickY) {
  59827. this.leftStick.y *= -1;
  59828. }
  59829. }
  59830. if (this._rightStick) {
  59831. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59832. }
  59833. };
  59834. Gamepad.prototype.dispose = function () {
  59835. };
  59836. Gamepad.GAMEPAD = 0;
  59837. Gamepad.GENERIC = 1;
  59838. Gamepad.XBOX = 2;
  59839. Gamepad.POSE_ENABLED = 3;
  59840. return Gamepad;
  59841. }());
  59842. BABYLON.Gamepad = Gamepad;
  59843. var GenericPad = /** @class */ (function (_super) {
  59844. __extends(GenericPad, _super);
  59845. function GenericPad(id, index, browserGamepad) {
  59846. var _this = _super.call(this, id, index, browserGamepad) || this;
  59847. _this.onButtonDownObservable = new BABYLON.Observable();
  59848. _this.onButtonUpObservable = new BABYLON.Observable();
  59849. _this.type = Gamepad.GENERIC;
  59850. _this._buttons = new Array(browserGamepad.buttons.length);
  59851. return _this;
  59852. }
  59853. GenericPad.prototype.onbuttondown = function (callback) {
  59854. this._onbuttondown = callback;
  59855. };
  59856. GenericPad.prototype.onbuttonup = function (callback) {
  59857. this._onbuttonup = callback;
  59858. };
  59859. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  59860. if (newValue !== currentValue) {
  59861. if (newValue === 1) {
  59862. if (this._onbuttondown) {
  59863. this._onbuttondown(buttonIndex);
  59864. }
  59865. this.onButtonDownObservable.notifyObservers(buttonIndex);
  59866. }
  59867. if (newValue === 0) {
  59868. if (this._onbuttonup) {
  59869. this._onbuttonup(buttonIndex);
  59870. }
  59871. this.onButtonUpObservable.notifyObservers(buttonIndex);
  59872. }
  59873. }
  59874. return newValue;
  59875. };
  59876. GenericPad.prototype.update = function () {
  59877. _super.prototype.update.call(this);
  59878. for (var index = 0; index < this._buttons.length; index++) {
  59879. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  59880. }
  59881. };
  59882. GenericPad.prototype.dispose = function () {
  59883. _super.prototype.dispose.call(this);
  59884. this.onButtonDownObservable.clear();
  59885. this.onButtonUpObservable.clear();
  59886. };
  59887. return GenericPad;
  59888. }(Gamepad));
  59889. BABYLON.GenericPad = GenericPad;
  59890. })(BABYLON || (BABYLON = {}));
  59891. //# sourceMappingURL=babylon.gamepad.js.map
  59892. var BABYLON;
  59893. (function (BABYLON) {
  59894. var Xbox360Button;
  59895. (function (Xbox360Button) {
  59896. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  59897. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  59898. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  59899. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  59900. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  59901. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  59902. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  59903. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  59904. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  59905. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  59906. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  59907. var Xbox360Dpad;
  59908. (function (Xbox360Dpad) {
  59909. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  59910. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  59911. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  59912. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  59913. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  59914. var Xbox360Pad = /** @class */ (function (_super) {
  59915. __extends(Xbox360Pad, _super);
  59916. function Xbox360Pad(id, index, gamepad, xboxOne) {
  59917. if (xboxOne === void 0) { xboxOne = false; }
  59918. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  59919. _this._leftTrigger = 0;
  59920. _this._rightTrigger = 0;
  59921. _this.onButtonDownObservable = new BABYLON.Observable();
  59922. _this.onButtonUpObservable = new BABYLON.Observable();
  59923. _this.onPadDownObservable = new BABYLON.Observable();
  59924. _this.onPadUpObservable = new BABYLON.Observable();
  59925. _this._buttonA = 0;
  59926. _this._buttonB = 0;
  59927. _this._buttonX = 0;
  59928. _this._buttonY = 0;
  59929. _this._buttonBack = 0;
  59930. _this._buttonStart = 0;
  59931. _this._buttonLB = 0;
  59932. _this._buttonRB = 0;
  59933. _this._buttonLeftStick = 0;
  59934. _this._buttonRightStick = 0;
  59935. _this._dPadUp = 0;
  59936. _this._dPadDown = 0;
  59937. _this._dPadLeft = 0;
  59938. _this._dPadRight = 0;
  59939. _this._isXboxOnePad = false;
  59940. _this.type = BABYLON.Gamepad.XBOX;
  59941. _this._isXboxOnePad = xboxOne;
  59942. return _this;
  59943. }
  59944. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  59945. this._onlefttriggerchanged = callback;
  59946. };
  59947. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  59948. this._onrighttriggerchanged = callback;
  59949. };
  59950. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  59951. get: function () {
  59952. return this._leftTrigger;
  59953. },
  59954. set: function (newValue) {
  59955. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  59956. this._onlefttriggerchanged(newValue);
  59957. }
  59958. this._leftTrigger = newValue;
  59959. },
  59960. enumerable: true,
  59961. configurable: true
  59962. });
  59963. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  59964. get: function () {
  59965. return this._rightTrigger;
  59966. },
  59967. set: function (newValue) {
  59968. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  59969. this._onrighttriggerchanged(newValue);
  59970. }
  59971. this._rightTrigger = newValue;
  59972. },
  59973. enumerable: true,
  59974. configurable: true
  59975. });
  59976. Xbox360Pad.prototype.onbuttondown = function (callback) {
  59977. this._onbuttondown = callback;
  59978. };
  59979. Xbox360Pad.prototype.onbuttonup = function (callback) {
  59980. this._onbuttonup = callback;
  59981. };
  59982. Xbox360Pad.prototype.ondpaddown = function (callback) {
  59983. this._ondpaddown = callback;
  59984. };
  59985. Xbox360Pad.prototype.ondpadup = function (callback) {
  59986. this._ondpadup = callback;
  59987. };
  59988. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  59989. if (newValue !== currentValue) {
  59990. if (newValue === 1) {
  59991. if (this._onbuttondown) {
  59992. this._onbuttondown(buttonType);
  59993. }
  59994. this.onButtonDownObservable.notifyObservers(buttonType);
  59995. }
  59996. if (newValue === 0) {
  59997. if (this._onbuttonup) {
  59998. this._onbuttonup(buttonType);
  59999. }
  60000. this.onButtonUpObservable.notifyObservers(buttonType);
  60001. }
  60002. }
  60003. return newValue;
  60004. };
  60005. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  60006. if (newValue !== currentValue) {
  60007. if (newValue === 1) {
  60008. if (this._ondpaddown) {
  60009. this._ondpaddown(buttonType);
  60010. }
  60011. this.onPadDownObservable.notifyObservers(buttonType);
  60012. }
  60013. if (newValue === 0) {
  60014. if (this._ondpadup) {
  60015. this._ondpadup(buttonType);
  60016. }
  60017. this.onPadUpObservable.notifyObservers(buttonType);
  60018. }
  60019. }
  60020. return newValue;
  60021. };
  60022. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  60023. get: function () {
  60024. return this._buttonA;
  60025. },
  60026. set: function (value) {
  60027. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  60028. },
  60029. enumerable: true,
  60030. configurable: true
  60031. });
  60032. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  60033. get: function () {
  60034. return this._buttonB;
  60035. },
  60036. set: function (value) {
  60037. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  60038. },
  60039. enumerable: true,
  60040. configurable: true
  60041. });
  60042. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  60043. get: function () {
  60044. return this._buttonX;
  60045. },
  60046. set: function (value) {
  60047. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  60048. },
  60049. enumerable: true,
  60050. configurable: true
  60051. });
  60052. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  60053. get: function () {
  60054. return this._buttonY;
  60055. },
  60056. set: function (value) {
  60057. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  60058. },
  60059. enumerable: true,
  60060. configurable: true
  60061. });
  60062. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  60063. get: function () {
  60064. return this._buttonStart;
  60065. },
  60066. set: function (value) {
  60067. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  60068. },
  60069. enumerable: true,
  60070. configurable: true
  60071. });
  60072. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  60073. get: function () {
  60074. return this._buttonBack;
  60075. },
  60076. set: function (value) {
  60077. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  60078. },
  60079. enumerable: true,
  60080. configurable: true
  60081. });
  60082. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  60083. get: function () {
  60084. return this._buttonLB;
  60085. },
  60086. set: function (value) {
  60087. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  60088. },
  60089. enumerable: true,
  60090. configurable: true
  60091. });
  60092. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  60093. get: function () {
  60094. return this._buttonRB;
  60095. },
  60096. set: function (value) {
  60097. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  60098. },
  60099. enumerable: true,
  60100. configurable: true
  60101. });
  60102. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  60103. get: function () {
  60104. return this._buttonLeftStick;
  60105. },
  60106. set: function (value) {
  60107. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  60108. },
  60109. enumerable: true,
  60110. configurable: true
  60111. });
  60112. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  60113. get: function () {
  60114. return this._buttonRightStick;
  60115. },
  60116. set: function (value) {
  60117. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  60118. },
  60119. enumerable: true,
  60120. configurable: true
  60121. });
  60122. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  60123. get: function () {
  60124. return this._dPadUp;
  60125. },
  60126. set: function (value) {
  60127. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  60128. },
  60129. enumerable: true,
  60130. configurable: true
  60131. });
  60132. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  60133. get: function () {
  60134. return this._dPadDown;
  60135. },
  60136. set: function (value) {
  60137. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  60138. },
  60139. enumerable: true,
  60140. configurable: true
  60141. });
  60142. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  60143. get: function () {
  60144. return this._dPadLeft;
  60145. },
  60146. set: function (value) {
  60147. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  60148. },
  60149. enumerable: true,
  60150. configurable: true
  60151. });
  60152. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  60153. get: function () {
  60154. return this._dPadRight;
  60155. },
  60156. set: function (value) {
  60157. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  60158. },
  60159. enumerable: true,
  60160. configurable: true
  60161. });
  60162. Xbox360Pad.prototype.update = function () {
  60163. _super.prototype.update.call(this);
  60164. if (this._isXboxOnePad) {
  60165. this.buttonA = this.browserGamepad.buttons[0].value;
  60166. this.buttonB = this.browserGamepad.buttons[1].value;
  60167. this.buttonX = this.browserGamepad.buttons[2].value;
  60168. this.buttonY = this.browserGamepad.buttons[3].value;
  60169. this.buttonLB = this.browserGamepad.buttons[4].value;
  60170. this.buttonRB = this.browserGamepad.buttons[5].value;
  60171. this.leftTrigger = this.browserGamepad.axes[2];
  60172. this.rightTrigger = this.browserGamepad.axes[5];
  60173. this.buttonBack = this.browserGamepad.buttons[9].value;
  60174. this.buttonStart = this.browserGamepad.buttons[8].value;
  60175. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  60176. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  60177. this.dPadUp = this.browserGamepad.buttons[11].value;
  60178. this.dPadDown = this.browserGamepad.buttons[12].value;
  60179. this.dPadLeft = this.browserGamepad.buttons[13].value;
  60180. this.dPadRight = this.browserGamepad.buttons[14].value;
  60181. }
  60182. else {
  60183. this.buttonA = this.browserGamepad.buttons[0].value;
  60184. this.buttonB = this.browserGamepad.buttons[1].value;
  60185. this.buttonX = this.browserGamepad.buttons[2].value;
  60186. this.buttonY = this.browserGamepad.buttons[3].value;
  60187. this.buttonLB = this.browserGamepad.buttons[4].value;
  60188. this.buttonRB = this.browserGamepad.buttons[5].value;
  60189. this.leftTrigger = this.browserGamepad.buttons[6].value;
  60190. this.rightTrigger = this.browserGamepad.buttons[7].value;
  60191. this.buttonBack = this.browserGamepad.buttons[8].value;
  60192. this.buttonStart = this.browserGamepad.buttons[9].value;
  60193. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  60194. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  60195. this.dPadUp = this.browserGamepad.buttons[12].value;
  60196. this.dPadDown = this.browserGamepad.buttons[13].value;
  60197. this.dPadLeft = this.browserGamepad.buttons[14].value;
  60198. this.dPadRight = this.browserGamepad.buttons[15].value;
  60199. }
  60200. };
  60201. Xbox360Pad.prototype.dispose = function () {
  60202. _super.prototype.dispose.call(this);
  60203. this.onButtonDownObservable.clear();
  60204. this.onButtonUpObservable.clear();
  60205. this.onPadDownObservable.clear();
  60206. this.onPadUpObservable.clear();
  60207. };
  60208. return Xbox360Pad;
  60209. }(BABYLON.Gamepad));
  60210. BABYLON.Xbox360Pad = Xbox360Pad;
  60211. })(BABYLON || (BABYLON = {}));
  60212. //# sourceMappingURL=babylon.xboxGamepad.js.map
  60213. var BABYLON;
  60214. (function (BABYLON) {
  60215. var PoseEnabledControllerType;
  60216. (function (PoseEnabledControllerType) {
  60217. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  60218. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  60219. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  60220. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  60221. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  60222. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  60223. var PoseEnabledControllerHelper = /** @class */ (function () {
  60224. function PoseEnabledControllerHelper() {
  60225. }
  60226. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  60227. // Oculus Touch
  60228. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  60229. return new BABYLON.OculusTouchController(vrGamepad);
  60230. }
  60231. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  60232. return new BABYLON.WindowsMotionController(vrGamepad);
  60233. }
  60234. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  60235. return new BABYLON.ViveController(vrGamepad);
  60236. }
  60237. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  60238. return new BABYLON.GearVRController(vrGamepad);
  60239. }
  60240. else {
  60241. return new BABYLON.GenericController(vrGamepad);
  60242. }
  60243. };
  60244. return PoseEnabledControllerHelper;
  60245. }());
  60246. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  60247. var PoseEnabledController = /** @class */ (function (_super) {
  60248. __extends(PoseEnabledController, _super);
  60249. function PoseEnabledController(browserGamepad) {
  60250. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  60251. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  60252. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  60253. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  60254. // Represents device position and rotation in babylon space
  60255. _this.devicePosition = BABYLON.Vector3.Zero();
  60256. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  60257. _this.deviceScaleFactor = 1;
  60258. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  60259. _this._deviceToWorld = BABYLON.Matrix.Identity();
  60260. _this._workingMatrix = BABYLON.Matrix.Identity();
  60261. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  60262. _this.controllerType = PoseEnabledControllerType.GENERIC;
  60263. _this.position = BABYLON.Vector3.Zero();
  60264. _this.rotationQuaternion = new BABYLON.Quaternion();
  60265. _this._calculatedPosition = BABYLON.Vector3.Zero();
  60266. _this._calculatedRotation = new BABYLON.Quaternion();
  60267. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  60268. return _this;
  60269. }
  60270. PoseEnabledController.prototype.update = function () {
  60271. _super.prototype.update.call(this);
  60272. var pose = this.browserGamepad.pose;
  60273. this.updateFromDevice(pose);
  60274. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  60275. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  60276. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  60277. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  60278. if (this._mesh) {
  60279. this._mesh.position.copyFrom(this.devicePosition);
  60280. if (this._mesh.rotationQuaternion) {
  60281. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  60282. }
  60283. }
  60284. };
  60285. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  60286. if (poseData) {
  60287. this.rawPose = poseData;
  60288. if (poseData.position) {
  60289. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  60290. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  60291. this._deviceRoomPosition.z *= -1;
  60292. }
  60293. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  60294. this._calculatedPosition.addInPlace(this.position);
  60295. }
  60296. var pose = this.rawPose;
  60297. if (poseData.orientation && pose.orientation) {
  60298. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  60299. if (this._mesh) {
  60300. if (this._mesh.getScene().useRightHandedSystem) {
  60301. this._deviceRoomRotationQuaternion.z *= -1;
  60302. this._deviceRoomRotationQuaternion.w *= -1;
  60303. }
  60304. else {
  60305. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  60306. }
  60307. }
  60308. // if the camera is set, rotate to the camera's rotation
  60309. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  60310. }
  60311. }
  60312. };
  60313. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  60314. if (this._mesh) {
  60315. this._mesh.parent = null;
  60316. }
  60317. this._mesh = mesh;
  60318. if (this._poseControlledCamera) {
  60319. this._mesh.parent = this._poseControlledCamera;
  60320. }
  60321. if (!this._mesh.rotationQuaternion) {
  60322. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  60323. }
  60324. };
  60325. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  60326. this._poseControlledCamera = camera;
  60327. if (this._mesh) {
  60328. this._mesh.parent = this._poseControlledCamera;
  60329. }
  60330. };
  60331. PoseEnabledController.prototype.dispose = function () {
  60332. if (this._mesh) {
  60333. this._mesh.dispose();
  60334. }
  60335. this._mesh = null;
  60336. _super.prototype.dispose.call(this);
  60337. };
  60338. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  60339. get: function () {
  60340. return this._mesh;
  60341. },
  60342. enumerable: true,
  60343. configurable: true
  60344. });
  60345. PoseEnabledController.prototype.getForwardRay = function (length) {
  60346. if (length === void 0) { length = 100; }
  60347. if (!this.mesh) {
  60348. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  60349. }
  60350. var m = this.mesh.getWorldMatrix();
  60351. var origin = m.getTranslation();
  60352. var forward = new BABYLON.Vector3(0, 0, -1);
  60353. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60354. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60355. return new BABYLON.Ray(origin, direction, length);
  60356. };
  60357. return PoseEnabledController;
  60358. }(BABYLON.Gamepad));
  60359. BABYLON.PoseEnabledController = PoseEnabledController;
  60360. })(BABYLON || (BABYLON = {}));
  60361. //# sourceMappingURL=babylon.poseEnabledController.js.map
  60362. var BABYLON;
  60363. (function (BABYLON) {
  60364. var WebVRController = /** @class */ (function (_super) {
  60365. __extends(WebVRController, _super);
  60366. function WebVRController(vrGamepad) {
  60367. var _this = _super.call(this, vrGamepad) || this;
  60368. // Observables
  60369. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  60370. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  60371. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  60372. _this.onPadStateChangedObservable = new BABYLON.Observable();
  60373. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  60374. _this.pad = { x: 0, y: 0 };
  60375. // avoid GC, store state in a tmp object
  60376. _this._changes = {
  60377. pressChanged: false,
  60378. touchChanged: false,
  60379. valueChanged: false,
  60380. changed: false
  60381. };
  60382. _this._buttons = new Array(vrGamepad.buttons.length);
  60383. _this.hand = vrGamepad.hand;
  60384. return _this;
  60385. }
  60386. WebVRController.prototype.onButtonStateChange = function (callback) {
  60387. this._onButtonStateChange = callback;
  60388. };
  60389. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  60390. get: function () {
  60391. return this._defaultModel;
  60392. },
  60393. enumerable: true,
  60394. configurable: true
  60395. });
  60396. WebVRController.prototype.update = function () {
  60397. _super.prototype.update.call(this);
  60398. for (var index = 0; index < this._buttons.length; index++) {
  60399. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  60400. }
  60401. ;
  60402. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  60403. this.pad.x = this.leftStick.x;
  60404. this.pad.y = this.leftStick.y;
  60405. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  60406. }
  60407. };
  60408. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  60409. if (!newState) {
  60410. newState = {
  60411. pressed: false,
  60412. touched: false,
  60413. value: 0
  60414. };
  60415. }
  60416. if (!currentState) {
  60417. this._buttons[buttonIndex] = {
  60418. pressed: newState.pressed,
  60419. touched: newState.touched,
  60420. value: newState.value
  60421. };
  60422. return;
  60423. }
  60424. this._checkChanges(newState, currentState);
  60425. if (this._changes.changed) {
  60426. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  60427. this.handleButtonChange(buttonIndex, newState, this._changes);
  60428. }
  60429. this._buttons[buttonIndex].pressed = newState.pressed;
  60430. this._buttons[buttonIndex].touched = newState.touched;
  60431. // oculus triggers are never 0, thou not touched.
  60432. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60433. };
  60434. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60435. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60436. this._changes.touchChanged = newState.touched !== currentState.touched;
  60437. this._changes.valueChanged = newState.value !== currentState.value;
  60438. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60439. return this._changes;
  60440. };
  60441. WebVRController.prototype.dispose = function () {
  60442. _super.prototype.dispose.call(this);
  60443. this.onTriggerStateChangedObservable.clear();
  60444. this.onMainButtonStateChangedObservable.clear();
  60445. this.onSecondaryButtonStateChangedObservable.clear();
  60446. this.onPadStateChangedObservable.clear();
  60447. this.onPadValuesChangedObservable.clear();
  60448. };
  60449. return WebVRController;
  60450. }(BABYLON.PoseEnabledController));
  60451. BABYLON.WebVRController = WebVRController;
  60452. })(BABYLON || (BABYLON = {}));
  60453. //# sourceMappingURL=babylon.webVRController.js.map
  60454. var BABYLON;
  60455. (function (BABYLON) {
  60456. var OculusTouchController = /** @class */ (function (_super) {
  60457. __extends(OculusTouchController, _super);
  60458. function OculusTouchController(vrGamepad) {
  60459. var _this = _super.call(this, vrGamepad) || this;
  60460. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60461. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60462. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60463. return _this;
  60464. }
  60465. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60466. var _this = this;
  60467. var meshName;
  60468. // Hand
  60469. if (this.hand === 'left') {
  60470. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60471. }
  60472. else {
  60473. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60474. }
  60475. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60476. /*
  60477. Parent Mesh name: oculus_touch_left
  60478. - body
  60479. - trigger
  60480. - thumbstick
  60481. - grip
  60482. - button_y
  60483. - button_x
  60484. - button_enter
  60485. */
  60486. _this._defaultModel = newMeshes[1];
  60487. _this.attachToMesh(_this._defaultModel);
  60488. if (meshLoaded) {
  60489. meshLoaded(_this._defaultModel);
  60490. }
  60491. });
  60492. };
  60493. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60494. // helper getters for left and right hand.
  60495. get: function () {
  60496. if (this.hand === 'right') {
  60497. return this.onMainButtonStateChangedObservable;
  60498. }
  60499. else {
  60500. throw new Error('No A button on left hand');
  60501. }
  60502. },
  60503. enumerable: true,
  60504. configurable: true
  60505. });
  60506. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60507. get: function () {
  60508. if (this.hand === 'right') {
  60509. return this.onSecondaryButtonStateChangedObservable;
  60510. }
  60511. else {
  60512. throw new Error('No B button on left hand');
  60513. }
  60514. },
  60515. enumerable: true,
  60516. configurable: true
  60517. });
  60518. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60519. get: function () {
  60520. if (this.hand === 'left') {
  60521. return this.onMainButtonStateChangedObservable;
  60522. }
  60523. else {
  60524. throw new Error('No X button on right hand');
  60525. }
  60526. },
  60527. enumerable: true,
  60528. configurable: true
  60529. });
  60530. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60531. get: function () {
  60532. if (this.hand === 'left') {
  60533. return this.onSecondaryButtonStateChangedObservable;
  60534. }
  60535. else {
  60536. throw new Error('No Y button on right hand');
  60537. }
  60538. },
  60539. enumerable: true,
  60540. configurable: true
  60541. });
  60542. /*
  60543. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60544. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60545. 2) secondary trigger (same)
  60546. 3) A (right) X (left), touch, pressed = value
  60547. 4) B / Y
  60548. 5) thumb rest
  60549. */
  60550. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60551. var notifyObject = state; //{ state: state, changes: changes };
  60552. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60553. switch (buttonIdx) {
  60554. case 0:
  60555. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60556. return;
  60557. case 1:// index trigger
  60558. if (this._defaultModel) {
  60559. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60560. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60561. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60562. }
  60563. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60564. return;
  60565. case 2:// secondary trigger
  60566. if (this._defaultModel) {
  60567. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60568. }
  60569. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60570. return;
  60571. case 3:
  60572. if (this._defaultModel) {
  60573. if (notifyObject.pressed) {
  60574. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60575. }
  60576. else {
  60577. (this._defaultModel.getChildren()[1]).position.y = 0;
  60578. }
  60579. }
  60580. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60581. return;
  60582. case 4:
  60583. if (this._defaultModel) {
  60584. if (notifyObject.pressed) {
  60585. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60586. }
  60587. else {
  60588. (this._defaultModel.getChildren()[2]).position.y = 0;
  60589. }
  60590. }
  60591. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60592. return;
  60593. case 5:
  60594. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60595. return;
  60596. }
  60597. };
  60598. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60599. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60600. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60601. return OculusTouchController;
  60602. }(BABYLON.WebVRController));
  60603. BABYLON.OculusTouchController = OculusTouchController;
  60604. })(BABYLON || (BABYLON = {}));
  60605. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60606. var BABYLON;
  60607. (function (BABYLON) {
  60608. var ViveController = /** @class */ (function (_super) {
  60609. __extends(ViveController, _super);
  60610. function ViveController(vrGamepad) {
  60611. var _this = _super.call(this, vrGamepad) || this;
  60612. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60613. _this._invertLeftStickY = true;
  60614. return _this;
  60615. }
  60616. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60617. var _this = this;
  60618. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60619. /*
  60620. Parent Mesh name: ViveWand
  60621. - body
  60622. - r_gripper
  60623. - l_gripper
  60624. - menu_button
  60625. - system_button
  60626. - trackpad
  60627. - trigger
  60628. - LED
  60629. */
  60630. _this._defaultModel = newMeshes[1];
  60631. _this.attachToMesh(_this._defaultModel);
  60632. if (meshLoaded) {
  60633. meshLoaded(_this._defaultModel);
  60634. }
  60635. });
  60636. };
  60637. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60638. get: function () {
  60639. return this.onMainButtonStateChangedObservable;
  60640. },
  60641. enumerable: true,
  60642. configurable: true
  60643. });
  60644. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60645. get: function () {
  60646. return this.onMainButtonStateChangedObservable;
  60647. },
  60648. enumerable: true,
  60649. configurable: true
  60650. });
  60651. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60652. get: function () {
  60653. return this.onSecondaryButtonStateChangedObservable;
  60654. },
  60655. enumerable: true,
  60656. configurable: true
  60657. });
  60658. /**
  60659. * Vive mapping:
  60660. * 0: touchpad
  60661. * 1: trigger
  60662. * 2: left AND right buttons
  60663. * 3: menu button
  60664. */
  60665. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60666. var notifyObject = state; //{ state: state, changes: changes };
  60667. switch (buttonIdx) {
  60668. case 0:
  60669. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60670. return;
  60671. case 1:// index trigger
  60672. if (this._defaultModel) {
  60673. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  60674. }
  60675. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60676. return;
  60677. case 2:// left AND right button
  60678. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60679. return;
  60680. case 3:
  60681. if (this._defaultModel) {
  60682. if (notifyObject.pressed) {
  60683. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60684. }
  60685. else {
  60686. (this._defaultModel.getChildren()[2]).position.y = 0;
  60687. }
  60688. }
  60689. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60690. return;
  60691. }
  60692. };
  60693. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  60694. ViveController.MODEL_FILENAME = 'wand.babylon';
  60695. return ViveController;
  60696. }(BABYLON.WebVRController));
  60697. BABYLON.ViveController = ViveController;
  60698. })(BABYLON || (BABYLON = {}));
  60699. //# sourceMappingURL=babylon.viveController.js.map
  60700. var BABYLON;
  60701. (function (BABYLON) {
  60702. var GenericController = /** @class */ (function (_super) {
  60703. __extends(GenericController, _super);
  60704. function GenericController(vrGamepad) {
  60705. return _super.call(this, vrGamepad) || this;
  60706. }
  60707. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60708. var _this = this;
  60709. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  60710. _this._defaultModel = newMeshes[1];
  60711. _this.attachToMesh(_this._defaultModel);
  60712. if (meshLoaded) {
  60713. meshLoaded(_this._defaultModel);
  60714. }
  60715. });
  60716. };
  60717. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60718. console.log("Button id: " + buttonIdx + "state: ");
  60719. console.dir(state);
  60720. };
  60721. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60722. GenericController.MODEL_FILENAME = 'generic.babylon';
  60723. return GenericController;
  60724. }(BABYLON.WebVRController));
  60725. BABYLON.GenericController = GenericController;
  60726. })(BABYLON || (BABYLON = {}));
  60727. //# sourceMappingURL=babylon.genericController.js.map
  60728. var BABYLON;
  60729. (function (BABYLON) {
  60730. var LoadedMeshInfo = /** @class */ (function () {
  60731. function LoadedMeshInfo() {
  60732. this.buttonMeshes = {};
  60733. this.axisMeshes = {};
  60734. }
  60735. return LoadedMeshInfo;
  60736. }());
  60737. var WindowsMotionController = /** @class */ (function (_super) {
  60738. __extends(WindowsMotionController, _super);
  60739. function WindowsMotionController(vrGamepad) {
  60740. var _this = _super.call(this, vrGamepad) || this;
  60741. _this._mapping = {
  60742. // Semantic button names
  60743. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  60744. // A mapping of the button name to glTF model node name
  60745. // that should be transformed by button value.
  60746. buttonMeshNames: {
  60747. 'trigger': 'SELECT',
  60748. 'menu': 'MENU',
  60749. 'grip': 'GRASP',
  60750. 'thumbstick': 'THUMBSTICK_PRESS',
  60751. 'trackpad': 'TOUCHPAD_PRESS'
  60752. },
  60753. // This mapping is used to translate from the Motion Controller to Babylon semantics
  60754. buttonObservableNames: {
  60755. 'trigger': 'onTriggerStateChangedObservable',
  60756. 'menu': 'onSecondaryButtonStateChangedObservable',
  60757. 'grip': 'onMainButtonStateChangedObservable',
  60758. 'thumbstick': 'onPadStateChangedObservable',
  60759. 'trackpad': 'onTrackpadChangedObservable'
  60760. },
  60761. // A mapping of the axis name to glTF model node name
  60762. // that should be transformed by axis value.
  60763. // This array mirrors the browserGamepad.axes array, such that
  60764. // the mesh corresponding to axis 0 is in this array index 0.
  60765. axisMeshNames: [
  60766. 'THUMBSTICK_X',
  60767. 'THUMBSTICK_Y',
  60768. 'TOUCHPAD_TOUCH_X',
  60769. 'TOUCHPAD_TOUCH_Y'
  60770. ],
  60771. pointingPoseMeshName: 'POINTING_POSE'
  60772. };
  60773. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  60774. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  60775. _this.trackpad = { x: 0, y: 0 };
  60776. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  60777. _this._loadedMeshInfo = null;
  60778. return _this;
  60779. }
  60780. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  60781. get: function () {
  60782. return this.onTriggerStateChangedObservable;
  60783. },
  60784. enumerable: true,
  60785. configurable: true
  60786. });
  60787. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  60788. get: function () {
  60789. return this.onSecondaryButtonStateChangedObservable;
  60790. },
  60791. enumerable: true,
  60792. configurable: true
  60793. });
  60794. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  60795. get: function () {
  60796. return this.onMainButtonStateChangedObservable;
  60797. },
  60798. enumerable: true,
  60799. configurable: true
  60800. });
  60801. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  60802. get: function () {
  60803. return this.onPadStateChangedObservable;
  60804. },
  60805. enumerable: true,
  60806. configurable: true
  60807. });
  60808. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  60809. get: function () {
  60810. return this.onTrackpadChangedObservable;
  60811. },
  60812. enumerable: true,
  60813. configurable: true
  60814. });
  60815. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  60816. get: function () {
  60817. return this.onTrackpadValuesChangedObservable;
  60818. },
  60819. enumerable: true,
  60820. configurable: true
  60821. });
  60822. /**
  60823. * Called once per frame by the engine.
  60824. */
  60825. WindowsMotionController.prototype.update = function () {
  60826. _super.prototype.update.call(this);
  60827. // Only need to animate axes if there is a loaded mesh
  60828. if (this._loadedMeshInfo) {
  60829. if (this.browserGamepad.axes) {
  60830. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  60831. this.trackpad.x = this.browserGamepad["axes"][2];
  60832. this.trackpad.y = this.browserGamepad["axes"][3];
  60833. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  60834. }
  60835. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  60836. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  60837. }
  60838. }
  60839. }
  60840. };
  60841. /**
  60842. * Called once for each button that changed state since the last frame
  60843. * @param buttonIdx Which button index changed
  60844. * @param state New state of the button
  60845. * @param changes Which properties on the state changed since last frame
  60846. */
  60847. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60848. var buttonName = this._mapping.buttons[buttonIdx];
  60849. if (!buttonName) {
  60850. return;
  60851. }
  60852. // Only emit events for buttons that we know how to map from index to name
  60853. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  60854. if (observable) {
  60855. observable.notifyObservers(state);
  60856. }
  60857. this.lerpButtonTransform(buttonName, state.value);
  60858. };
  60859. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  60860. // If there is no loaded mesh, there is nothing to transform.
  60861. if (!this._loadedMeshInfo) {
  60862. return;
  60863. }
  60864. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  60865. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60866. return;
  60867. }
  60868. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  60869. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  60870. };
  60871. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  60872. if (!this._loadedMeshInfo) {
  60873. return;
  60874. }
  60875. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  60876. if (!meshInfo) {
  60877. return;
  60878. }
  60879. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60880. return;
  60881. }
  60882. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  60883. var lerpValue = axisValue * 0.5 + 0.5;
  60884. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  60885. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  60886. };
  60887. /**
  60888. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  60889. * @param scene scene in which to add meshes
  60890. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  60891. */
  60892. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  60893. var _this = this;
  60894. if (forceDefault === void 0) { forceDefault = false; }
  60895. var path;
  60896. var filename;
  60897. // Checking if GLB loader is present
  60898. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  60899. // Determine the device specific folder based on the ID suffix
  60900. var device = 'default';
  60901. if (this.id && !forceDefault) {
  60902. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  60903. device = ((match && match[0]) || device);
  60904. }
  60905. // Hand
  60906. if (this.hand === 'left') {
  60907. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  60908. }
  60909. else {
  60910. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  60911. }
  60912. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  60913. }
  60914. else {
  60915. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  60916. path = BABYLON.GenericController.MODEL_BASE_URL;
  60917. filename = BABYLON.GenericController.MODEL_FILENAME;
  60918. }
  60919. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  60920. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  60921. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  60922. if (!_this._loadedMeshInfo) {
  60923. return;
  60924. }
  60925. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  60926. _this.attachToMesh(_this._defaultModel);
  60927. if (meshLoaded) {
  60928. meshLoaded(_this._defaultModel);
  60929. }
  60930. }, null, function (scene, message) {
  60931. BABYLON.Tools.Log(message);
  60932. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  60933. if (!forceDefault) {
  60934. _this.initControllerMesh(scene, meshLoaded, true);
  60935. }
  60936. });
  60937. };
  60938. /**
  60939. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  60940. * can be transformed by button presses and axes values, based on this._mapping.
  60941. *
  60942. * @param scene scene in which the meshes exist
  60943. * @param meshes list of meshes that make up the controller model to process
  60944. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  60945. */
  60946. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  60947. var loadedMeshInfo = null;
  60948. // Create a new mesh to contain the glTF hierarchy
  60949. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  60950. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  60951. var childMesh = null;
  60952. for (var i = 0; i < meshes.length; i++) {
  60953. var mesh = meshes[i];
  60954. if (!mesh.parent) {
  60955. // Exclude controller meshes from picking results
  60956. mesh.isPickable = false;
  60957. // Handle root node, attach to the new parentMesh
  60958. childMesh = mesh;
  60959. break;
  60960. }
  60961. }
  60962. if (childMesh) {
  60963. childMesh.setParent(parentMesh);
  60964. // Create our mesh info. Note that this method will always return non-null.
  60965. loadedMeshInfo = this.createMeshInfo(parentMesh);
  60966. }
  60967. else {
  60968. BABYLON.Tools.Warn('Could not find root node in model file.');
  60969. }
  60970. return loadedMeshInfo;
  60971. };
  60972. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  60973. var loadedMeshInfo = new LoadedMeshInfo();
  60974. var i;
  60975. loadedMeshInfo.rootNode = rootNode;
  60976. // Reset the caches
  60977. loadedMeshInfo.buttonMeshes = {};
  60978. loadedMeshInfo.axisMeshes = {};
  60979. // Button Meshes
  60980. for (i = 0; i < this._mapping.buttons.length; i++) {
  60981. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  60982. if (!buttonMeshName) {
  60983. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  60984. continue;
  60985. }
  60986. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  60987. if (!buttonMesh) {
  60988. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  60989. continue;
  60990. }
  60991. var buttonMeshInfo = {
  60992. index: i,
  60993. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  60994. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  60995. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  60996. };
  60997. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  60998. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  60999. }
  61000. else {
  61001. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  61002. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  61003. '(VALUE: ' + !!buttonMeshInfo.value +
  61004. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  61005. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  61006. ')');
  61007. }
  61008. }
  61009. // Axis Meshes
  61010. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  61011. var axisMeshName = this._mapping.axisMeshNames[i];
  61012. if (!axisMeshName) {
  61013. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  61014. continue;
  61015. }
  61016. var axisMesh = getChildByName(rootNode, axisMeshName);
  61017. if (!axisMesh) {
  61018. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  61019. continue;
  61020. }
  61021. var axisMeshInfo = {
  61022. index: i,
  61023. value: getImmediateChildByName(axisMesh, 'VALUE'),
  61024. min: getImmediateChildByName(axisMesh, 'MIN'),
  61025. max: getImmediateChildByName(axisMesh, 'MAX')
  61026. };
  61027. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  61028. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  61029. }
  61030. else {
  61031. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  61032. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  61033. '(VALUE: ' + !!axisMeshInfo.value +
  61034. ', MIN: ' + !!axisMeshInfo.min +
  61035. ', MAX:' + !!axisMeshInfo.max +
  61036. ')');
  61037. }
  61038. }
  61039. // Pointing Ray
  61040. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  61041. if (!loadedMeshInfo.pointingPoseNode) {
  61042. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  61043. }
  61044. return loadedMeshInfo;
  61045. // Look through all children recursively. This will return null if no mesh exists with the given name.
  61046. function getChildByName(node, name) {
  61047. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  61048. }
  61049. // Look through only immediate children. This will return null if no mesh exists with the given name.
  61050. function getImmediateChildByName(node, name) {
  61051. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  61052. }
  61053. };
  61054. WindowsMotionController.prototype.getForwardRay = function (length) {
  61055. if (length === void 0) { length = 100; }
  61056. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  61057. return _super.prototype.getForwardRay.call(this, length);
  61058. }
  61059. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  61060. var origin = m.getTranslation();
  61061. var forward = new BABYLON.Vector3(0, 0, -1);
  61062. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61063. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61064. return new BABYLON.Ray(origin, direction, length);
  61065. };
  61066. WindowsMotionController.prototype.dispose = function () {
  61067. _super.prototype.dispose.call(this);
  61068. this.onTrackpadChangedObservable.clear();
  61069. };
  61070. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  61071. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  61072. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  61073. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  61074. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  61075. return WindowsMotionController;
  61076. }(BABYLON.WebVRController));
  61077. BABYLON.WindowsMotionController = WindowsMotionController;
  61078. })(BABYLON || (BABYLON = {}));
  61079. //# sourceMappingURL=babylon.windowsMotionController.js.map
  61080. var BABYLON;
  61081. (function (BABYLON) {
  61082. var GearVRController = /** @class */ (function (_super) {
  61083. __extends(GearVRController, _super);
  61084. function GearVRController(vrGamepad) {
  61085. var _this = _super.call(this, vrGamepad) || this;
  61086. _this._buttonIndexToObservableNameMap = [
  61087. 'onTrackpadChangedObservable',
  61088. 'onTriggerStateChangedObservable' // Trigger
  61089. ];
  61090. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  61091. return _this;
  61092. }
  61093. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61094. var _this = this;
  61095. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  61096. _this._defaultModel = newMeshes[1];
  61097. _this.attachToMesh(_this._defaultModel);
  61098. if (meshLoaded) {
  61099. meshLoaded(_this._defaultModel);
  61100. }
  61101. });
  61102. };
  61103. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61104. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  61105. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  61106. // Only emit events for buttons that we know how to map from index to observable
  61107. var observable = this[observableName];
  61108. if (observable) {
  61109. observable.notifyObservers(state);
  61110. }
  61111. }
  61112. };
  61113. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61114. GearVRController.MODEL_FILENAME = 'generic.babylon';
  61115. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  61116. return GearVRController;
  61117. }(BABYLON.WebVRController));
  61118. BABYLON.GearVRController = GearVRController;
  61119. })(BABYLON || (BABYLON = {}));
  61120. //# sourceMappingURL=babylon.gearVRController.js.map
  61121. var BABYLON;
  61122. (function (BABYLON) {
  61123. var FollowCamera = /** @class */ (function (_super) {
  61124. __extends(FollowCamera, _super);
  61125. function FollowCamera(name, position, scene, lockedTarget) {
  61126. if (lockedTarget === void 0) { lockedTarget = null; }
  61127. var _this = _super.call(this, name, position, scene) || this;
  61128. _this.radius = 12;
  61129. _this.rotationOffset = 0;
  61130. _this.heightOffset = 4;
  61131. _this.cameraAcceleration = 0.05;
  61132. _this.maxCameraSpeed = 20;
  61133. _this.lockedTarget = lockedTarget;
  61134. return _this;
  61135. }
  61136. FollowCamera.prototype.getRadians = function (degrees) {
  61137. return degrees * Math.PI / 180;
  61138. };
  61139. FollowCamera.prototype.follow = function (cameraTarget) {
  61140. if (!cameraTarget)
  61141. return;
  61142. var yRotation;
  61143. if (cameraTarget.rotationQuaternion) {
  61144. var rotMatrix = new BABYLON.Matrix();
  61145. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  61146. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  61147. }
  61148. else {
  61149. yRotation = cameraTarget.rotation.y;
  61150. }
  61151. var radians = this.getRadians(this.rotationOffset) + yRotation;
  61152. var targetPosition = cameraTarget.getAbsolutePosition();
  61153. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  61154. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  61155. var dx = targetX - this.position.x;
  61156. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  61157. var dz = (targetZ) - this.position.z;
  61158. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  61159. var vy = dy * this.cameraAcceleration;
  61160. var vz = dz * this.cameraAcceleration * 2;
  61161. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  61162. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61163. }
  61164. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  61165. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61166. }
  61167. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  61168. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61169. }
  61170. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  61171. this.setTarget(targetPosition);
  61172. };
  61173. FollowCamera.prototype._checkInputs = function () {
  61174. _super.prototype._checkInputs.call(this);
  61175. if (this.lockedTarget) {
  61176. this.follow(this.lockedTarget);
  61177. }
  61178. };
  61179. FollowCamera.prototype.getClassName = function () {
  61180. return "FollowCamera";
  61181. };
  61182. __decorate([
  61183. BABYLON.serialize()
  61184. ], FollowCamera.prototype, "radius", void 0);
  61185. __decorate([
  61186. BABYLON.serialize()
  61187. ], FollowCamera.prototype, "rotationOffset", void 0);
  61188. __decorate([
  61189. BABYLON.serialize()
  61190. ], FollowCamera.prototype, "heightOffset", void 0);
  61191. __decorate([
  61192. BABYLON.serialize()
  61193. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  61194. __decorate([
  61195. BABYLON.serialize()
  61196. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  61197. __decorate([
  61198. BABYLON.serializeAsMeshReference("lockedTargetId")
  61199. ], FollowCamera.prototype, "lockedTarget", void 0);
  61200. return FollowCamera;
  61201. }(BABYLON.TargetCamera));
  61202. BABYLON.FollowCamera = FollowCamera;
  61203. var ArcFollowCamera = /** @class */ (function (_super) {
  61204. __extends(ArcFollowCamera, _super);
  61205. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  61206. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  61207. _this.alpha = alpha;
  61208. _this.beta = beta;
  61209. _this.radius = radius;
  61210. _this.target = target;
  61211. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  61212. _this.follow();
  61213. return _this;
  61214. }
  61215. ArcFollowCamera.prototype.follow = function () {
  61216. if (!this.target) {
  61217. return;
  61218. }
  61219. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  61220. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  61221. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  61222. var targetPosition = this.target.getAbsolutePosition();
  61223. this.position = targetPosition.add(this._cartesianCoordinates);
  61224. this.setTarget(targetPosition);
  61225. };
  61226. ArcFollowCamera.prototype._checkInputs = function () {
  61227. _super.prototype._checkInputs.call(this);
  61228. this.follow();
  61229. };
  61230. ArcFollowCamera.prototype.getClassName = function () {
  61231. return "ArcFollowCamera";
  61232. };
  61233. return ArcFollowCamera;
  61234. }(BABYLON.TargetCamera));
  61235. BABYLON.ArcFollowCamera = ArcFollowCamera;
  61236. })(BABYLON || (BABYLON = {}));
  61237. //# sourceMappingURL=babylon.followCamera.js.map
  61238. var BABYLON;
  61239. (function (BABYLON) {
  61240. // We're mainly based on the logic defined into the FreeCamera code
  61241. var UniversalCamera = /** @class */ (function (_super) {
  61242. __extends(UniversalCamera, _super);
  61243. //-- end properties for backward compatibility for inputs
  61244. function UniversalCamera(name, position, scene) {
  61245. var _this = _super.call(this, name, position, scene) || this;
  61246. _this.inputs.addGamepad();
  61247. return _this;
  61248. }
  61249. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  61250. //-- Begin properties for backward compatibility for inputs
  61251. get: function () {
  61252. var gamepad = this.inputs.attached["gamepad"];
  61253. if (gamepad)
  61254. return gamepad.gamepadAngularSensibility;
  61255. return 0;
  61256. },
  61257. set: function (value) {
  61258. var gamepad = this.inputs.attached["gamepad"];
  61259. if (gamepad)
  61260. gamepad.gamepadAngularSensibility = value;
  61261. },
  61262. enumerable: true,
  61263. configurable: true
  61264. });
  61265. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  61266. get: function () {
  61267. var gamepad = this.inputs.attached["gamepad"];
  61268. if (gamepad)
  61269. return gamepad.gamepadMoveSensibility;
  61270. return 0;
  61271. },
  61272. set: function (value) {
  61273. var gamepad = this.inputs.attached["gamepad"];
  61274. if (gamepad)
  61275. gamepad.gamepadMoveSensibility = value;
  61276. },
  61277. enumerable: true,
  61278. configurable: true
  61279. });
  61280. UniversalCamera.prototype.getClassName = function () {
  61281. return "UniversalCamera";
  61282. };
  61283. return UniversalCamera;
  61284. }(BABYLON.TouchCamera));
  61285. BABYLON.UniversalCamera = UniversalCamera;
  61286. })(BABYLON || (BABYLON = {}));
  61287. //# sourceMappingURL=babylon.universalCamera.js.map
  61288. var BABYLON;
  61289. (function (BABYLON) {
  61290. // We're mainly based on the logic defined into the FreeCamera code
  61291. var GamepadCamera = /** @class */ (function (_super) {
  61292. __extends(GamepadCamera, _super);
  61293. //-- end properties for backward compatibility for inputs
  61294. function GamepadCamera(name, position, scene) {
  61295. return _super.call(this, name, position, scene) || this;
  61296. }
  61297. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  61298. //-- Begin properties for backward compatibility for inputs
  61299. get: function () {
  61300. var gamepad = this.inputs.attached["gamepad"];
  61301. if (gamepad)
  61302. return gamepad.gamepadAngularSensibility;
  61303. return 0;
  61304. },
  61305. set: function (value) {
  61306. var gamepad = this.inputs.attached["gamepad"];
  61307. if (gamepad)
  61308. gamepad.gamepadAngularSensibility = value;
  61309. },
  61310. enumerable: true,
  61311. configurable: true
  61312. });
  61313. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  61314. get: function () {
  61315. var gamepad = this.inputs.attached["gamepad"];
  61316. if (gamepad)
  61317. return gamepad.gamepadMoveSensibility;
  61318. return 0;
  61319. },
  61320. set: function (value) {
  61321. var gamepad = this.inputs.attached["gamepad"];
  61322. if (gamepad)
  61323. gamepad.gamepadMoveSensibility = value;
  61324. },
  61325. enumerable: true,
  61326. configurable: true
  61327. });
  61328. GamepadCamera.prototype.getClassName = function () {
  61329. return "GamepadCamera";
  61330. };
  61331. return GamepadCamera;
  61332. }(BABYLON.UniversalCamera));
  61333. BABYLON.GamepadCamera = GamepadCamera;
  61334. })(BABYLON || (BABYLON = {}));
  61335. //# sourceMappingURL=babylon.gamepadCamera.js.map
  61336. var BABYLON;
  61337. (function (BABYLON) {
  61338. var PostProcessRenderPipelineManager = /** @class */ (function () {
  61339. function PostProcessRenderPipelineManager() {
  61340. this._renderPipelines = {};
  61341. }
  61342. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  61343. this._renderPipelines[renderPipeline._name] = renderPipeline;
  61344. };
  61345. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  61346. if (unique === void 0) { unique = false; }
  61347. var renderPipeline = this._renderPipelines[renderPipelineName];
  61348. if (!renderPipeline) {
  61349. return;
  61350. }
  61351. renderPipeline._attachCameras(cameras, unique);
  61352. };
  61353. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  61354. var renderPipeline = this._renderPipelines[renderPipelineName];
  61355. if (!renderPipeline) {
  61356. return;
  61357. }
  61358. renderPipeline._detachCameras(cameras);
  61359. };
  61360. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61361. var renderPipeline = this._renderPipelines[renderPipelineName];
  61362. if (!renderPipeline) {
  61363. return;
  61364. }
  61365. renderPipeline._enableEffect(renderEffectName, cameras);
  61366. };
  61367. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61368. var renderPipeline = this._renderPipelines[renderPipelineName];
  61369. if (!renderPipeline) {
  61370. return;
  61371. }
  61372. renderPipeline._disableEffect(renderEffectName, cameras);
  61373. };
  61374. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  61375. var renderPipeline = this._renderPipelines[renderPipelineName];
  61376. if (!renderPipeline) {
  61377. return;
  61378. }
  61379. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  61380. };
  61381. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  61382. var renderPipeline = this._renderPipelines[renderPipelineName];
  61383. if (!renderPipeline) {
  61384. return;
  61385. }
  61386. renderPipeline._disableDisplayOnlyPass(cameras);
  61387. };
  61388. PostProcessRenderPipelineManager.prototype.update = function () {
  61389. for (var renderPipelineName in this._renderPipelines) {
  61390. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61391. var pipeline = this._renderPipelines[renderPipelineName];
  61392. if (!pipeline.isSupported) {
  61393. pipeline.dispose();
  61394. delete this._renderPipelines[renderPipelineName];
  61395. }
  61396. else {
  61397. pipeline._update();
  61398. }
  61399. }
  61400. }
  61401. };
  61402. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  61403. for (var renderPipelineName in this._renderPipelines) {
  61404. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61405. var pipeline = this._renderPipelines[renderPipelineName];
  61406. pipeline._rebuild();
  61407. }
  61408. }
  61409. };
  61410. PostProcessRenderPipelineManager.prototype.dispose = function () {
  61411. for (var renderPipelineName in this._renderPipelines) {
  61412. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61413. var pipeline = this._renderPipelines[renderPipelineName];
  61414. pipeline.dispose();
  61415. }
  61416. }
  61417. };
  61418. return PostProcessRenderPipelineManager;
  61419. }());
  61420. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  61421. })(BABYLON || (BABYLON = {}));
  61422. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  61423. var BABYLON;
  61424. (function (BABYLON) {
  61425. var PostProcessRenderPass = /** @class */ (function () {
  61426. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  61427. this._refCount = 0;
  61428. this._name = name;
  61429. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  61430. this.setRenderList(renderList);
  61431. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  61432. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61433. this._scene = scene;
  61434. this._renderList = renderList;
  61435. }
  61436. // private
  61437. PostProcessRenderPass.prototype._incRefCount = function () {
  61438. if (this._refCount === 0) {
  61439. this._scene.customRenderTargets.push(this._renderTexture);
  61440. }
  61441. return ++this._refCount;
  61442. };
  61443. PostProcessRenderPass.prototype._decRefCount = function () {
  61444. this._refCount--;
  61445. if (this._refCount <= 0) {
  61446. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61447. }
  61448. return this._refCount;
  61449. };
  61450. PostProcessRenderPass.prototype._update = function () {
  61451. this.setRenderList(this._renderList);
  61452. };
  61453. // public
  61454. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61455. this._renderTexture.renderList = renderList;
  61456. };
  61457. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61458. return this._renderTexture;
  61459. };
  61460. return PostProcessRenderPass;
  61461. }());
  61462. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61463. })(BABYLON || (BABYLON = {}));
  61464. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61465. var BABYLON;
  61466. (function (BABYLON) {
  61467. var PostProcessRenderEffect = /** @class */ (function () {
  61468. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61469. this._name = name;
  61470. this._singleInstance = singleInstance || true;
  61471. this._getPostProcess = getPostProcess;
  61472. this._cameras = {};
  61473. this._indicesForCamera = {};
  61474. this._postProcesses = {};
  61475. this._renderPasses = {};
  61476. this._renderEffectAsPasses = {};
  61477. }
  61478. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61479. get: function () {
  61480. for (var index in this._postProcesses) {
  61481. if (!this._postProcesses[index].isSupported) {
  61482. return false;
  61483. }
  61484. }
  61485. return true;
  61486. },
  61487. enumerable: true,
  61488. configurable: true
  61489. });
  61490. PostProcessRenderEffect.prototype._update = function () {
  61491. for (var renderPassName in this._renderPasses) {
  61492. this._renderPasses[renderPassName]._update();
  61493. }
  61494. };
  61495. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61496. this._renderPasses[renderPass._name] = renderPass;
  61497. this._linkParameters();
  61498. };
  61499. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61500. delete this._renderPasses[renderPass._name];
  61501. this._linkParameters();
  61502. };
  61503. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61504. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61505. this._linkParameters();
  61506. };
  61507. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61508. for (var renderPassName in this._renderPasses) {
  61509. if (renderPassName === passName) {
  61510. return this._renderPasses[passName];
  61511. }
  61512. }
  61513. return null;
  61514. };
  61515. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61516. this._renderPasses = {};
  61517. this._linkParameters();
  61518. };
  61519. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61520. var cameraKey;
  61521. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61522. if (!cams) {
  61523. return;
  61524. }
  61525. for (var i = 0; i < cams.length; i++) {
  61526. var camera = cams[i];
  61527. var cameraName = camera.name;
  61528. if (this._singleInstance) {
  61529. cameraKey = 0;
  61530. }
  61531. else {
  61532. cameraKey = cameraName;
  61533. }
  61534. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61535. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61536. if (!this._indicesForCamera[cameraName]) {
  61537. this._indicesForCamera[cameraName] = [];
  61538. }
  61539. this._indicesForCamera[cameraName].push(index);
  61540. if (!this._cameras[cameraName]) {
  61541. this._cameras[cameraName] = camera;
  61542. }
  61543. for (var passName in this._renderPasses) {
  61544. this._renderPasses[passName]._incRefCount();
  61545. }
  61546. }
  61547. this._linkParameters();
  61548. };
  61549. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61550. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61551. if (!cams) {
  61552. return;
  61553. }
  61554. for (var i = 0; i < cams.length; i++) {
  61555. var camera = cams[i];
  61556. var cameraName = camera.name;
  61557. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61558. if (this._cameras[cameraName]) {
  61559. //this._indicesForCamera.splice(index, 1);
  61560. this._cameras[cameraName] = null;
  61561. }
  61562. for (var passName in this._renderPasses) {
  61563. this._renderPasses[passName]._decRefCount();
  61564. }
  61565. }
  61566. };
  61567. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61568. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61569. if (!cams) {
  61570. return;
  61571. }
  61572. for (var i = 0; i < cams.length; i++) {
  61573. var camera = cams[i];
  61574. var cameraName = camera.name;
  61575. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61576. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61577. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61578. }
  61579. }
  61580. for (var passName in this._renderPasses) {
  61581. this._renderPasses[passName]._incRefCount();
  61582. }
  61583. }
  61584. };
  61585. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61586. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61587. if (!cams) {
  61588. return;
  61589. }
  61590. for (var i = 0; i < cams.length; i++) {
  61591. var camera = cams[i];
  61592. var cameraName = camera.Name;
  61593. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61594. for (var passName in this._renderPasses) {
  61595. this._renderPasses[passName]._decRefCount();
  61596. }
  61597. }
  61598. };
  61599. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61600. if (this._singleInstance) {
  61601. return this._postProcesses[0];
  61602. }
  61603. else {
  61604. if (!camera) {
  61605. return null;
  61606. }
  61607. return this._postProcesses[camera.name];
  61608. }
  61609. };
  61610. PostProcessRenderEffect.prototype._linkParameters = function () {
  61611. var _this = this;
  61612. for (var index in this._postProcesses) {
  61613. if (this.applyParameters) {
  61614. this.applyParameters(this._postProcesses[index]);
  61615. }
  61616. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61617. _this._linkTextures(effect);
  61618. });
  61619. }
  61620. };
  61621. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61622. for (var renderPassName in this._renderPasses) {
  61623. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61624. }
  61625. for (var renderEffectName in this._renderEffectAsPasses) {
  61626. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61627. }
  61628. };
  61629. return PostProcessRenderEffect;
  61630. }());
  61631. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61632. })(BABYLON || (BABYLON = {}));
  61633. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61634. var BABYLON;
  61635. (function (BABYLON) {
  61636. var PostProcessRenderPipeline = /** @class */ (function () {
  61637. function PostProcessRenderPipeline(engine, name) {
  61638. this._engine = engine;
  61639. this._name = name;
  61640. this._renderEffects = {};
  61641. this._renderEffectsForIsolatedPass = new Array();
  61642. this._cameras = [];
  61643. }
  61644. PostProcessRenderPipeline.prototype.getClassName = function () {
  61645. return "PostProcessRenderPipeline";
  61646. };
  61647. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61648. get: function () {
  61649. for (var renderEffectName in this._renderEffects) {
  61650. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61651. if (!this._renderEffects[renderEffectName].isSupported) {
  61652. return false;
  61653. }
  61654. }
  61655. }
  61656. return true;
  61657. },
  61658. enumerable: true,
  61659. configurable: true
  61660. });
  61661. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61662. this._renderEffects[renderEffect._name] = renderEffect;
  61663. };
  61664. // private
  61665. PostProcessRenderPipeline.prototype._rebuild = function () {
  61666. };
  61667. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  61668. var renderEffects = this._renderEffects[renderEffectName];
  61669. if (!renderEffects) {
  61670. return;
  61671. }
  61672. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61673. };
  61674. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  61675. var renderEffects = this._renderEffects[renderEffectName];
  61676. if (!renderEffects) {
  61677. return;
  61678. }
  61679. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61680. };
  61681. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  61682. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61683. if (!cams) {
  61684. return;
  61685. }
  61686. var indicesToDelete = [];
  61687. var i;
  61688. for (i = 0; i < cams.length; i++) {
  61689. var camera = cams[i];
  61690. var cameraName = camera.name;
  61691. if (this._cameras.indexOf(camera) === -1) {
  61692. this._cameras[cameraName] = camera;
  61693. }
  61694. else if (unique) {
  61695. indicesToDelete.push(i);
  61696. }
  61697. }
  61698. for (i = 0; i < indicesToDelete.length; i++) {
  61699. cameras.splice(indicesToDelete[i], 1);
  61700. }
  61701. for (var renderEffectName in this._renderEffects) {
  61702. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61703. this._renderEffects[renderEffectName]._attachCameras(cams);
  61704. }
  61705. }
  61706. };
  61707. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  61708. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61709. if (!cams) {
  61710. return;
  61711. }
  61712. for (var renderEffectName in this._renderEffects) {
  61713. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61714. this._renderEffects[renderEffectName]._detachCameras(cams);
  61715. }
  61716. }
  61717. for (var i = 0; i < cams.length; i++) {
  61718. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  61719. }
  61720. };
  61721. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  61722. var _this = this;
  61723. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61724. if (!cams) {
  61725. return;
  61726. }
  61727. var pass = null;
  61728. var renderEffectName;
  61729. for (renderEffectName in this._renderEffects) {
  61730. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61731. pass = this._renderEffects[renderEffectName].getPass(passName);
  61732. if (pass != null) {
  61733. break;
  61734. }
  61735. }
  61736. }
  61737. if (pass === null) {
  61738. return;
  61739. }
  61740. for (renderEffectName in this._renderEffects) {
  61741. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61742. this._renderEffects[renderEffectName]._disable(cams);
  61743. }
  61744. }
  61745. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  61746. for (var i = 0; i < cams.length; i++) {
  61747. var camera = cams[i];
  61748. var cameraName = camera.name;
  61749. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  61750. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  61751. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  61752. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  61753. }
  61754. };
  61755. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  61756. var _this = this;
  61757. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61758. if (!cams) {
  61759. return;
  61760. }
  61761. for (var i = 0; i < cams.length; i++) {
  61762. var camera = cams[i];
  61763. var cameraName = camera.name;
  61764. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  61765. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  61766. }
  61767. for (var renderEffectName in this._renderEffects) {
  61768. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61769. this._renderEffects[renderEffectName]._enable(cams);
  61770. }
  61771. }
  61772. };
  61773. PostProcessRenderPipeline.prototype._update = function () {
  61774. for (var renderEffectName in this._renderEffects) {
  61775. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61776. this._renderEffects[renderEffectName]._update();
  61777. }
  61778. }
  61779. for (var i = 0; i < this._cameras.length; i++) {
  61780. var cameraName = this._cameras[i].name;
  61781. if (this._renderEffectsForIsolatedPass[cameraName]) {
  61782. this._renderEffectsForIsolatedPass[cameraName]._update();
  61783. }
  61784. }
  61785. };
  61786. PostProcessRenderPipeline.prototype._reset = function () {
  61787. this._renderEffects = {};
  61788. this._renderEffectsForIsolatedPass = new Array();
  61789. };
  61790. PostProcessRenderPipeline.prototype.dispose = function () {
  61791. // Must be implemented by children
  61792. };
  61793. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  61794. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  61795. __decorate([
  61796. BABYLON.serialize()
  61797. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  61798. return PostProcessRenderPipeline;
  61799. }());
  61800. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  61801. })(BABYLON || (BABYLON = {}));
  61802. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  61803. var BABYLON;
  61804. (function (BABYLON) {
  61805. var DepthRenderer = /** @class */ (function () {
  61806. function DepthRenderer(scene, type) {
  61807. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  61808. var _this = this;
  61809. this._scene = scene;
  61810. var engine = scene.getEngine();
  61811. // Render target
  61812. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  61813. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61814. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61815. this._depthMap.refreshRate = 1;
  61816. this._depthMap.renderParticles = false;
  61817. this._depthMap.renderList = null;
  61818. // set default depth value to 1.0 (far away)
  61819. this._depthMap.onClearObservable.add(function (engine) {
  61820. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  61821. });
  61822. // Custom render function
  61823. var renderSubMesh = function (subMesh) {
  61824. var mesh = subMesh.getRenderingMesh();
  61825. var scene = _this._scene;
  61826. var engine = scene.getEngine();
  61827. var material = subMesh.getMaterial();
  61828. if (!material) {
  61829. return;
  61830. }
  61831. // Culling and reverse (right handed system)
  61832. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61833. // Managing instances
  61834. var batch = mesh._getInstancesRenderList(subMesh._id);
  61835. if (batch.mustReturn) {
  61836. return;
  61837. }
  61838. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61839. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  61840. engine.enableEffect(_this._effect);
  61841. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61842. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61843. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  61844. // Alpha test
  61845. if (material && material.needAlphaTesting()) {
  61846. var alphaTexture = material.getAlphaTestTexture();
  61847. if (alphaTexture) {
  61848. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61849. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61850. }
  61851. }
  61852. // Bones
  61853. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61854. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61855. }
  61856. // Draw
  61857. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61858. }
  61859. };
  61860. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61861. var index;
  61862. if (depthOnlySubMeshes.length) {
  61863. engine.setColorWrite(false);
  61864. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61865. renderSubMesh(depthOnlySubMeshes.data[index]);
  61866. }
  61867. engine.setColorWrite(true);
  61868. }
  61869. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61870. renderSubMesh(opaqueSubMeshes.data[index]);
  61871. }
  61872. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61873. renderSubMesh(alphaTestSubMeshes.data[index]);
  61874. }
  61875. };
  61876. }
  61877. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  61878. var material = subMesh.getMaterial();
  61879. if (material.disableDepthWrite) {
  61880. return false;
  61881. }
  61882. var defines = [];
  61883. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61884. var mesh = subMesh.getMesh();
  61885. // Alpha test
  61886. if (material && material.needAlphaTesting()) {
  61887. defines.push("#define ALPHATEST");
  61888. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61889. attribs.push(BABYLON.VertexBuffer.UVKind);
  61890. defines.push("#define UV1");
  61891. }
  61892. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61893. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61894. defines.push("#define UV2");
  61895. }
  61896. }
  61897. // Bones
  61898. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61899. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61900. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61901. if (mesh.numBoneInfluencers > 4) {
  61902. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61903. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61904. }
  61905. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61906. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61907. }
  61908. else {
  61909. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61910. }
  61911. // Instances
  61912. if (useInstances) {
  61913. defines.push("#define INSTANCES");
  61914. attribs.push("world0");
  61915. attribs.push("world1");
  61916. attribs.push("world2");
  61917. attribs.push("world3");
  61918. }
  61919. // Get correct effect
  61920. var join = defines.join("\n");
  61921. if (this._cachedDefines !== join) {
  61922. this._cachedDefines = join;
  61923. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  61924. }
  61925. return this._effect.isReady();
  61926. };
  61927. DepthRenderer.prototype.getDepthMap = function () {
  61928. return this._depthMap;
  61929. };
  61930. // Methods
  61931. DepthRenderer.prototype.dispose = function () {
  61932. this._depthMap.dispose();
  61933. };
  61934. return DepthRenderer;
  61935. }());
  61936. BABYLON.DepthRenderer = DepthRenderer;
  61937. })(BABYLON || (BABYLON = {}));
  61938. //# sourceMappingURL=babylon.depthRenderer.js.map
  61939. var BABYLON;
  61940. (function (BABYLON) {
  61941. var SSAORenderingPipeline = /** @class */ (function (_super) {
  61942. __extends(SSAORenderingPipeline, _super);
  61943. /**
  61944. * @constructor
  61945. * @param {string} name - The rendering pipeline name
  61946. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61947. * @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 }
  61948. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61949. */
  61950. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  61951. var _this = _super.call(this, scene.getEngine(), name) || this;
  61952. // Members
  61953. /**
  61954. * The PassPostProcess id in the pipeline that contains the original scene color
  61955. * @type {string}
  61956. */
  61957. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  61958. /**
  61959. * The SSAO PostProcess id in the pipeline
  61960. * @type {string}
  61961. */
  61962. _this.SSAORenderEffect = "SSAORenderEffect";
  61963. /**
  61964. * The horizontal blur PostProcess id in the pipeline
  61965. * @type {string}
  61966. */
  61967. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  61968. /**
  61969. * The vertical blur PostProcess id in the pipeline
  61970. * @type {string}
  61971. */
  61972. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  61973. /**
  61974. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  61975. * @type {string}
  61976. */
  61977. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  61978. /**
  61979. * The output strength of the SSAO post-process. Default value is 1.0.
  61980. * @type {number}
  61981. */
  61982. _this.totalStrength = 1.0;
  61983. /**
  61984. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  61985. * @type {number}
  61986. */
  61987. _this.radius = 0.0001;
  61988. /**
  61989. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  61990. * Must not be equal to fallOff and superior to fallOff.
  61991. * Default value is 0.975
  61992. * @type {number}
  61993. */
  61994. _this.area = 0.0075;
  61995. /**
  61996. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  61997. * Must not be equal to area and inferior to area.
  61998. * Default value is 0.0
  61999. * @type {number}
  62000. */
  62001. _this.fallOff = 0.000001;
  62002. /**
  62003. * The base color of the SSAO post-process
  62004. * The final result is "base + ssao" between [0, 1]
  62005. * @type {number}
  62006. */
  62007. _this.base = 0.5;
  62008. _this._firstUpdate = true;
  62009. _this._scene = scene;
  62010. // Set up assets
  62011. _this._createRandomTexture();
  62012. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62013. var ssaoRatio = ratio.ssaoRatio || ratio;
  62014. var combineRatio = ratio.combineRatio || ratio;
  62015. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62016. _this._createSSAOPostProcess(ssaoRatio);
  62017. _this._createBlurPostProcess(ssaoRatio);
  62018. _this._createSSAOCombinePostProcess(combineRatio);
  62019. // Set up pipeline
  62020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62021. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62022. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62023. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62024. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62025. // Finish
  62026. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62027. if (cameras)
  62028. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62029. return _this;
  62030. }
  62031. // Public Methods
  62032. /**
  62033. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62034. */
  62035. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62036. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62037. for (var i = 0; i < this._scene.cameras.length; i++) {
  62038. var camera = this._scene.cameras[i];
  62039. this._originalColorPostProcess.dispose(camera);
  62040. this._ssaoPostProcess.dispose(camera);
  62041. this._blurHPostProcess.dispose(camera);
  62042. this._blurVPostProcess.dispose(camera);
  62043. this._ssaoCombinePostProcess.dispose(camera);
  62044. }
  62045. this._randomTexture.dispose();
  62046. if (disableDepthRender)
  62047. this._scene.disableDepthRenderer();
  62048. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62049. _super.prototype.dispose.call(this);
  62050. };
  62051. // Private Methods
  62052. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62053. var _this = this;
  62054. var size = 16;
  62055. 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);
  62056. 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);
  62057. this._blurHPostProcess.onActivateObservable.add(function () {
  62058. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62059. _this._blurHPostProcess.kernel = size * dw;
  62060. });
  62061. this._blurVPostProcess.onActivateObservable.add(function () {
  62062. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62063. _this._blurVPostProcess.kernel = size * dw;
  62064. });
  62065. };
  62066. SSAORenderingPipeline.prototype._rebuild = function () {
  62067. this._firstUpdate = true;
  62068. _super.prototype._rebuild.call(this);
  62069. };
  62070. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62071. var _this = this;
  62072. var numSamples = 16;
  62073. var sampleSphere = [
  62074. 0.5381, 0.1856, -0.4319,
  62075. 0.1379, 0.2486, 0.4430,
  62076. 0.3371, 0.5679, -0.0057,
  62077. -0.6999, -0.0451, -0.0019,
  62078. 0.0689, -0.1598, -0.8547,
  62079. 0.0560, 0.0069, -0.1843,
  62080. -0.0146, 0.1402, 0.0762,
  62081. 0.0100, -0.1924, -0.0344,
  62082. -0.3577, -0.5301, -0.4358,
  62083. -0.3169, 0.1063, 0.0158,
  62084. 0.0103, -0.5869, 0.0046,
  62085. -0.0897, -0.4940, 0.3287,
  62086. 0.7119, -0.0154, -0.0918,
  62087. -0.0533, 0.0596, -0.5411,
  62088. 0.0352, -0.0631, 0.5460,
  62089. -0.4776, 0.2847, -0.0271
  62090. ];
  62091. var samplesFactor = 1.0 / numSamples;
  62092. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  62093. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62094. "area", "fallOff", "base", "range", "viewport"
  62095. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62096. this._ssaoPostProcess.onApply = function (effect) {
  62097. if (_this._firstUpdate) {
  62098. effect.setArray3("sampleSphere", sampleSphere);
  62099. effect.setFloat("samplesFactor", samplesFactor);
  62100. effect.setFloat("randTextureTiles", 4.0);
  62101. }
  62102. effect.setFloat("totalStrength", _this.totalStrength);
  62103. effect.setFloat("radius", _this.radius);
  62104. effect.setFloat("area", _this.area);
  62105. effect.setFloat("fallOff", _this.fallOff);
  62106. effect.setFloat("base", _this.base);
  62107. effect.setTexture("textureSampler", _this._depthTexture);
  62108. effect.setTexture("randomSampler", _this._randomTexture);
  62109. };
  62110. };
  62111. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62112. var _this = this;
  62113. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62114. this._ssaoCombinePostProcess.onApply = function (effect) {
  62115. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62116. };
  62117. };
  62118. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  62119. var size = 512;
  62120. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62121. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62122. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62123. var context = this._randomTexture.getContext();
  62124. var rand = function (min, max) {
  62125. return Math.random() * (max - min) + min;
  62126. };
  62127. var randVector = BABYLON.Vector3.Zero();
  62128. for (var x = 0; x < size; x++) {
  62129. for (var y = 0; y < size; y++) {
  62130. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  62131. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  62132. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  62133. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62134. context.fillRect(x, y, 1, 1);
  62135. }
  62136. }
  62137. this._randomTexture.update(false);
  62138. };
  62139. __decorate([
  62140. BABYLON.serialize()
  62141. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  62142. __decorate([
  62143. BABYLON.serialize()
  62144. ], SSAORenderingPipeline.prototype, "radius", void 0);
  62145. __decorate([
  62146. BABYLON.serialize()
  62147. ], SSAORenderingPipeline.prototype, "area", void 0);
  62148. __decorate([
  62149. BABYLON.serialize()
  62150. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  62151. __decorate([
  62152. BABYLON.serialize()
  62153. ], SSAORenderingPipeline.prototype, "base", void 0);
  62154. return SSAORenderingPipeline;
  62155. }(BABYLON.PostProcessRenderPipeline));
  62156. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  62157. })(BABYLON || (BABYLON = {}));
  62158. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  62159. var BABYLON;
  62160. (function (BABYLON) {
  62161. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  62162. __extends(SSAO2RenderingPipeline, _super);
  62163. /**
  62164. * @constructor
  62165. * @param {string} name - The rendering pipeline name
  62166. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62167. * @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 }
  62168. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62169. */
  62170. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  62171. var _this = _super.call(this, scene.getEngine(), name) || this;
  62172. // Members
  62173. /**
  62174. * The PassPostProcess id in the pipeline that contains the original scene color
  62175. * @type {string}
  62176. */
  62177. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62178. /**
  62179. * The SSAO PostProcess id in the pipeline
  62180. * @type {string}
  62181. */
  62182. _this.SSAORenderEffect = "SSAORenderEffect";
  62183. /**
  62184. * The horizontal blur PostProcess id in the pipeline
  62185. * @type {string}
  62186. */
  62187. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62188. /**
  62189. * The vertical blur PostProcess id in the pipeline
  62190. * @type {string}
  62191. */
  62192. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62193. /**
  62194. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62195. * @type {string}
  62196. */
  62197. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62198. /**
  62199. * The output strength of the SSAO post-process. Default value is 1.0.
  62200. * @type {number}
  62201. */
  62202. _this.totalStrength = 1.0;
  62203. /**
  62204. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  62205. * @type {number}
  62206. */
  62207. _this.maxZ = 100.0;
  62208. /**
  62209. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  62210. * @type {number}
  62211. */
  62212. _this.minZAspect = 0.2;
  62213. /**
  62214. * Number of samples used for the SSAO calculations. Default value is 8
  62215. * @type {number}
  62216. */
  62217. _this._samples = 8;
  62218. /**
  62219. * Are we using bilateral blur ?
  62220. * @type {boolean}
  62221. */
  62222. _this._expensiveBlur = true;
  62223. /**
  62224. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  62225. * @type {number}
  62226. */
  62227. _this.radius = 2.0;
  62228. /**
  62229. * The base color of the SSAO post-process
  62230. * The final result is "base + ssao" between [0, 1]
  62231. * @type {number}
  62232. */
  62233. _this.base = 0.1;
  62234. _this._firstUpdate = true;
  62235. _this._scene = scene;
  62236. if (!_this.isSupported) {
  62237. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  62238. return _this;
  62239. }
  62240. var ssaoRatio = ratio.ssaoRatio || ratio;
  62241. var blurRatio = ratio.blurRatio || ratio;
  62242. // Set up assets
  62243. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  62244. _this._createRandomTexture();
  62245. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  62246. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  62247. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62248. _this._createSSAOPostProcess(1.0);
  62249. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  62250. _this._createSSAOCombinePostProcess(blurRatio);
  62251. // Set up pipeline
  62252. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62253. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62254. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62255. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62256. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62257. // Finish
  62258. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62259. if (cameras)
  62260. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62261. return _this;
  62262. }
  62263. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62264. get: function () {
  62265. return this._samples;
  62266. },
  62267. set: function (n) {
  62268. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  62269. this._samples = n;
  62270. this._sampleSphere = this._generateHemisphere();
  62271. this._firstUpdate = true;
  62272. },
  62273. enumerable: true,
  62274. configurable: true
  62275. });
  62276. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  62277. get: function () {
  62278. return this._expensiveBlur;
  62279. },
  62280. set: function (b) {
  62281. 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"]);
  62282. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  62283. this._expensiveBlur = b;
  62284. this._firstUpdate = true;
  62285. },
  62286. enumerable: true,
  62287. configurable: true
  62288. });
  62289. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  62290. /**
  62291. * Support test.
  62292. * @type {boolean}
  62293. */
  62294. get: function () {
  62295. var engine = BABYLON.Engine.LastCreatedEngine;
  62296. if (!engine) {
  62297. return false;
  62298. }
  62299. return engine.getCaps().drawBuffersExtension;
  62300. },
  62301. enumerable: true,
  62302. configurable: true
  62303. });
  62304. // Public Methods
  62305. /**
  62306. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62307. */
  62308. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  62309. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  62310. for (var i = 0; i < this._scene.cameras.length; i++) {
  62311. var camera = this._scene.cameras[i];
  62312. this._originalColorPostProcess.dispose(camera);
  62313. this._ssaoPostProcess.dispose(camera);
  62314. this._blurHPostProcess.dispose(camera);
  62315. this._blurVPostProcess.dispose(camera);
  62316. this._ssaoCombinePostProcess.dispose(camera);
  62317. }
  62318. this._randomTexture.dispose();
  62319. if (disableGeometryBufferRenderer)
  62320. this._scene.disableGeometryBufferRenderer();
  62321. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62322. _super.prototype.dispose.call(this);
  62323. };
  62324. // Private Methods
  62325. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  62326. var _this = this;
  62327. this._samplerOffsets = [];
  62328. var expensive = this.expensiveBlur;
  62329. for (var i = -8; i < 8; i++) {
  62330. this._samplerOffsets.push(i * 2 + 0.5);
  62331. }
  62332. 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");
  62333. this._blurHPostProcess.onApply = function (effect) {
  62334. if (!_this._scene.activeCamera) {
  62335. return;
  62336. }
  62337. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  62338. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62339. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62340. effect.setFloat("radius", _this.radius);
  62341. effect.setTexture("depthSampler", _this._depthTexture);
  62342. if (_this._firstUpdate) {
  62343. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62344. }
  62345. };
  62346. 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");
  62347. this._blurVPostProcess.onApply = function (effect) {
  62348. if (!_this._scene.activeCamera) {
  62349. return;
  62350. }
  62351. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  62352. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62353. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62354. effect.setFloat("radius", _this.radius);
  62355. effect.setTexture("depthSampler", _this._depthTexture);
  62356. if (_this._firstUpdate) {
  62357. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62358. _this._firstUpdate = false;
  62359. }
  62360. };
  62361. };
  62362. SSAO2RenderingPipeline.prototype._rebuild = function () {
  62363. this._firstUpdate = true;
  62364. _super.prototype._rebuild.call(this);
  62365. };
  62366. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  62367. var numSamples = this.samples;
  62368. var result = [];
  62369. var vector, scale;
  62370. var rand = function (min, max) {
  62371. return Math.random() * (max - min) + min;
  62372. };
  62373. var i = 0;
  62374. while (i < numSamples) {
  62375. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  62376. vector.normalize();
  62377. scale = i / numSamples;
  62378. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  62379. vector.scaleInPlace(scale);
  62380. result.push(vector.x, vector.y, vector.z);
  62381. i++;
  62382. }
  62383. return result;
  62384. };
  62385. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62386. var _this = this;
  62387. var numSamples = this.samples;
  62388. this._sampleSphere = this._generateHemisphere();
  62389. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  62390. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62391. "base", "range", "projection", "near", "far", "texelSize",
  62392. "xViewport", "yViewport", "maxZ", "minZAspect"
  62393. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62394. this._ssaoPostProcess.onApply = function (effect) {
  62395. if (_this._firstUpdate) {
  62396. effect.setArray3("sampleSphere", _this._sampleSphere);
  62397. effect.setFloat("randTextureTiles", 4.0);
  62398. }
  62399. if (!_this._scene.activeCamera) {
  62400. return;
  62401. }
  62402. effect.setFloat("samplesFactor", 1 / _this.samples);
  62403. effect.setFloat("totalStrength", _this.totalStrength);
  62404. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  62405. effect.setFloat("radius", _this.radius);
  62406. effect.setFloat("maxZ", _this.maxZ);
  62407. effect.setFloat("minZAspect", _this.minZAspect);
  62408. effect.setFloat("base", _this.base);
  62409. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62410. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62411. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  62412. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  62413. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  62414. effect.setTexture("textureSampler", _this._depthTexture);
  62415. effect.setTexture("normalSampler", _this._normalTexture);
  62416. effect.setTexture("randomSampler", _this._randomTexture);
  62417. };
  62418. };
  62419. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62420. var _this = this;
  62421. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62422. this._ssaoCombinePostProcess.onApply = function (effect) {
  62423. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62424. };
  62425. };
  62426. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  62427. var size = 512;
  62428. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62429. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62430. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62431. var context = this._randomTexture.getContext();
  62432. var rand = function (min, max) {
  62433. return Math.random() * (max - min) + min;
  62434. };
  62435. var randVector = BABYLON.Vector3.Zero();
  62436. for (var x = 0; x < size; x++) {
  62437. for (var y = 0; y < size; y++) {
  62438. randVector.x = rand(0.0, 1.0);
  62439. randVector.y = rand(0.0, 1.0);
  62440. randVector.z = 0.0;
  62441. randVector.normalize();
  62442. randVector.scaleInPlace(255);
  62443. randVector.x = Math.floor(randVector.x);
  62444. randVector.y = Math.floor(randVector.y);
  62445. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62446. context.fillRect(x, y, 1, 1);
  62447. }
  62448. }
  62449. this._randomTexture.update(false);
  62450. };
  62451. __decorate([
  62452. BABYLON.serialize()
  62453. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62454. __decorate([
  62455. BABYLON.serialize()
  62456. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62457. __decorate([
  62458. BABYLON.serialize()
  62459. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62460. __decorate([
  62461. BABYLON.serialize("samples")
  62462. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62463. __decorate([
  62464. BABYLON.serialize("expensiveBlur")
  62465. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62466. __decorate([
  62467. BABYLON.serialize()
  62468. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62469. __decorate([
  62470. BABYLON.serialize()
  62471. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62472. return SSAO2RenderingPipeline;
  62473. }(BABYLON.PostProcessRenderPipeline));
  62474. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62475. })(BABYLON || (BABYLON = {}));
  62476. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62477. // BABYLON.JS Chromatic Aberration GLSL Shader
  62478. // Author: Olivier Guyot
  62479. // Separates very slightly R, G and B colors on the edges of the screen
  62480. // Inspired by Francois Tarlier & Martins Upitis
  62481. var BABYLON;
  62482. (function (BABYLON) {
  62483. var LensRenderingPipeline = /** @class */ (function (_super) {
  62484. __extends(LensRenderingPipeline, _super);
  62485. /**
  62486. * @constructor
  62487. *
  62488. * Effect parameters are as follow:
  62489. * {
  62490. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62491. * edge_blur: number; // from 0 to x (1 for realism)
  62492. * distortion: number; // from 0 to x (1 for realism)
  62493. * grain_amount: number; // from 0 to 1
  62494. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62495. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62496. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62497. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62498. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62499. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62500. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62501. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62502. * }
  62503. * Note: if an effect parameter is unset, effect is disabled
  62504. *
  62505. * @param {string} name - The rendering pipeline name
  62506. * @param {object} parameters - An object containing all parameters (see above)
  62507. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62508. * @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)
  62509. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62510. */
  62511. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62512. if (ratio === void 0) { ratio = 1.0; }
  62513. var _this = _super.call(this, scene.getEngine(), name) || this;
  62514. // Lens effects can be of the following:
  62515. // - chromatic aberration (slight shift of RGB colors)
  62516. // - blur on the edge of the lens
  62517. // - lens distortion
  62518. // - depth-of-field blur & highlights enhancing
  62519. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62520. // - grain effect (noise or custom texture)
  62521. // Two additional texture samplers are needed:
  62522. // - depth map (for depth-of-field)
  62523. // - grain texture
  62524. /**
  62525. * The chromatic aberration PostProcess id in the pipeline
  62526. * @type {string}
  62527. */
  62528. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62529. /**
  62530. * The highlights enhancing PostProcess id in the pipeline
  62531. * @type {string}
  62532. */
  62533. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62534. /**
  62535. * The depth-of-field PostProcess id in the pipeline
  62536. * @type {string}
  62537. */
  62538. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62539. _this._scene = scene;
  62540. // Fetch texture samplers
  62541. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62542. if (parameters.grain_texture) {
  62543. _this._grainTexture = parameters.grain_texture;
  62544. }
  62545. else {
  62546. _this._createGrainTexture();
  62547. }
  62548. // save parameters
  62549. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62550. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62551. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62552. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62553. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62554. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62555. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62556. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62557. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62558. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62559. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62560. // Create effects
  62561. _this._createChromaticAberrationPostProcess(ratio);
  62562. _this._createHighlightsPostProcess(ratio);
  62563. _this._createDepthOfFieldPostProcess(ratio / 4);
  62564. // Set up pipeline
  62565. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62566. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62567. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62568. if (_this._highlightsGain === -1) {
  62569. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62570. }
  62571. // Finish
  62572. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62573. if (cameras) {
  62574. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62575. }
  62576. return _this;
  62577. }
  62578. // public methods (self explanatory)
  62579. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62580. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62581. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62582. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62583. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62584. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62585. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62586. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62587. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62588. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62589. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62590. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62591. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62592. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62593. };
  62594. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62595. this._highlightsPostProcess.updateEffect();
  62596. };
  62597. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62598. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62599. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62600. this._highlightsGain = amount;
  62601. };
  62602. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62603. if (this._highlightsGain === -1) {
  62604. this._highlightsGain = 1.0;
  62605. }
  62606. this._highlightsThreshold = amount;
  62607. };
  62608. LensRenderingPipeline.prototype.disableHighlights = function () {
  62609. this._highlightsGain = -1;
  62610. };
  62611. /**
  62612. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62613. */
  62614. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62615. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62616. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62617. this._chromaticAberrationPostProcess = null;
  62618. this._highlightsPostProcess = null;
  62619. this._depthOfFieldPostProcess = null;
  62620. this._grainTexture.dispose();
  62621. if (disableDepthRender)
  62622. this._scene.disableDepthRenderer();
  62623. };
  62624. // colors shifting and distortion
  62625. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62626. var _this = this;
  62627. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62628. [], // samplers
  62629. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62630. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62631. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62632. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62633. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62634. };
  62635. };
  62636. // highlights enhancing
  62637. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62638. var _this = this;
  62639. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62640. [], // samplers
  62641. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62642. this._highlightsPostProcess.onApply = function (effect) {
  62643. effect.setFloat('gain', _this._highlightsGain);
  62644. effect.setFloat('threshold', _this._highlightsThreshold);
  62645. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62646. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62647. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62648. };
  62649. };
  62650. // colors shifting and distortion
  62651. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62652. var _this = this;
  62653. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62654. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62655. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62656. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62657. this._depthOfFieldPostProcess.onApply = function (effect) {
  62658. effect.setTexture("depthSampler", _this._depthTexture);
  62659. effect.setTexture("grainSampler", _this._grainTexture);
  62660. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62661. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62662. effect.setFloat('grain_amount', _this._grainAmount);
  62663. effect.setBool('blur_noise', _this._blurNoise);
  62664. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62665. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62666. effect.setFloat('distortion', _this._distortion);
  62667. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  62668. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  62669. effect.setFloat('aperture', _this._dofAperture);
  62670. effect.setFloat('darken', _this._dofDarken);
  62671. effect.setFloat('edge_blur', _this._edgeBlur);
  62672. effect.setBool('highlights', (_this._highlightsGain !== -1));
  62673. if (_this._scene.activeCamera) {
  62674. effect.setFloat('near', _this._scene.activeCamera.minZ);
  62675. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  62676. }
  62677. };
  62678. };
  62679. // creates a black and white random noise texture, 512x512
  62680. LensRenderingPipeline.prototype._createGrainTexture = function () {
  62681. var size = 512;
  62682. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62683. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62684. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62685. var context = this._grainTexture.getContext();
  62686. var rand = function (min, max) {
  62687. return Math.random() * (max - min) + min;
  62688. };
  62689. var value;
  62690. for (var x = 0; x < size; x++) {
  62691. for (var y = 0; y < size; y++) {
  62692. value = Math.floor(rand(0.42, 0.58) * 255);
  62693. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  62694. context.fillRect(x, y, 1, 1);
  62695. }
  62696. }
  62697. this._grainTexture.update(false);
  62698. };
  62699. return LensRenderingPipeline;
  62700. }(BABYLON.PostProcessRenderPipeline));
  62701. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  62702. })(BABYLON || (BABYLON = {}));
  62703. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  62704. var BABYLON;
  62705. (function (BABYLON) {
  62706. var StandardRenderingPipeline = /** @class */ (function (_super) {
  62707. __extends(StandardRenderingPipeline, _super);
  62708. /**
  62709. * @constructor
  62710. * @param {string} name - The rendering pipeline name
  62711. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62712. * @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)
  62713. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62714. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62715. */
  62716. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62717. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62718. var _this = _super.call(this, scene.getEngine(), name) || this;
  62719. _this.downSampleX4PostProcess = null;
  62720. _this.brightPassPostProcess = null;
  62721. _this.blurHPostProcesses = [];
  62722. _this.blurVPostProcesses = [];
  62723. _this.textureAdderPostProcess = null;
  62724. _this.volumetricLightPostProcess = null;
  62725. _this.volumetricLightSmoothXPostProcess = null;
  62726. _this.volumetricLightSmoothYPostProcess = null;
  62727. _this.volumetricLightMergePostProces = null;
  62728. _this.volumetricLightFinalPostProcess = null;
  62729. _this.luminancePostProcess = null;
  62730. _this.luminanceDownSamplePostProcesses = [];
  62731. _this.hdrPostProcess = null;
  62732. _this.textureAdderFinalPostProcess = null;
  62733. _this.lensFlareFinalPostProcess = null;
  62734. _this.hdrFinalPostProcess = null;
  62735. _this.lensFlarePostProcess = null;
  62736. _this.lensFlareComposePostProcess = null;
  62737. _this.motionBlurPostProcess = null;
  62738. _this.depthOfFieldPostProcess = null;
  62739. // Values
  62740. _this.brightThreshold = 1.0;
  62741. _this.blurWidth = 512.0;
  62742. _this.horizontalBlur = false;
  62743. _this.exposure = 1.0;
  62744. _this.lensTexture = null;
  62745. _this.volumetricLightCoefficient = 0.2;
  62746. _this.volumetricLightPower = 4.0;
  62747. _this.volumetricLightBlurScale = 64.0;
  62748. _this.sourceLight = null;
  62749. _this.hdrMinimumLuminance = 1.0;
  62750. _this.hdrDecreaseRate = 0.5;
  62751. _this.hdrIncreaseRate = 0.5;
  62752. _this.lensColorTexture = null;
  62753. _this.lensFlareStrength = 20.0;
  62754. _this.lensFlareGhostDispersal = 1.4;
  62755. _this.lensFlareHaloWidth = 0.7;
  62756. _this.lensFlareDistortionStrength = 16.0;
  62757. _this.lensStarTexture = null;
  62758. _this.lensFlareDirtTexture = null;
  62759. _this.depthOfFieldDistance = 10.0;
  62760. _this.depthOfFieldBlurWidth = 64.0;
  62761. _this.motionStrength = 1.0;
  62762. // IAnimatable
  62763. _this.animations = [];
  62764. _this._currentDepthOfFieldSource = null;
  62765. _this._hdrCurrentLuminance = 1.0;
  62766. // Getters and setters
  62767. _this._bloomEnabled = true;
  62768. _this._depthOfFieldEnabled = false;
  62769. _this._vlsEnabled = false;
  62770. _this._lensFlareEnabled = false;
  62771. _this._hdrEnabled = false;
  62772. _this._motionBlurEnabled = false;
  62773. _this._motionBlurSamples = 64.0;
  62774. _this._volumetricLightStepsCount = 50.0;
  62775. _this._cameras = cameras || [];
  62776. // Initialize
  62777. _this._scene = scene;
  62778. _this._basePostProcess = originalPostProcess;
  62779. _this._ratio = ratio;
  62780. // Misc
  62781. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62782. // Finish
  62783. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62784. _this._buildPipeline();
  62785. return _this;
  62786. }
  62787. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  62788. get: function () {
  62789. return this._bloomEnabled;
  62790. },
  62791. set: function (enabled) {
  62792. if (this._bloomEnabled === enabled) {
  62793. return;
  62794. }
  62795. this._bloomEnabled = enabled;
  62796. this._buildPipeline();
  62797. },
  62798. enumerable: true,
  62799. configurable: true
  62800. });
  62801. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62802. get: function () {
  62803. return this._depthOfFieldEnabled;
  62804. },
  62805. set: function (enabled) {
  62806. if (this._depthOfFieldEnabled === enabled) {
  62807. return;
  62808. }
  62809. this._depthOfFieldEnabled = enabled;
  62810. this._buildPipeline();
  62811. },
  62812. enumerable: true,
  62813. configurable: true
  62814. });
  62815. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  62816. get: function () {
  62817. return this._lensFlareEnabled;
  62818. },
  62819. set: function (enabled) {
  62820. if (this._lensFlareEnabled === enabled) {
  62821. return;
  62822. }
  62823. this._lensFlareEnabled = enabled;
  62824. this._buildPipeline();
  62825. },
  62826. enumerable: true,
  62827. configurable: true
  62828. });
  62829. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  62830. get: function () {
  62831. return this._hdrEnabled;
  62832. },
  62833. set: function (enabled) {
  62834. if (this._hdrEnabled === enabled) {
  62835. return;
  62836. }
  62837. this._hdrEnabled = enabled;
  62838. this._buildPipeline();
  62839. },
  62840. enumerable: true,
  62841. configurable: true
  62842. });
  62843. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  62844. get: function () {
  62845. return this._vlsEnabled;
  62846. },
  62847. set: function (enabled) {
  62848. if (this._vlsEnabled === enabled) {
  62849. return;
  62850. }
  62851. if (enabled) {
  62852. var geometry = this._scene.enableGeometryBufferRenderer();
  62853. if (!geometry) {
  62854. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  62855. return;
  62856. }
  62857. }
  62858. this._vlsEnabled = enabled;
  62859. this._buildPipeline();
  62860. },
  62861. enumerable: true,
  62862. configurable: true
  62863. });
  62864. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  62865. get: function () {
  62866. return this._motionBlurEnabled;
  62867. },
  62868. set: function (enabled) {
  62869. if (this._motionBlurEnabled === enabled) {
  62870. return;
  62871. }
  62872. this._motionBlurEnabled = enabled;
  62873. this._buildPipeline();
  62874. },
  62875. enumerable: true,
  62876. configurable: true
  62877. });
  62878. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  62879. get: function () {
  62880. return this._volumetricLightStepsCount;
  62881. },
  62882. set: function (count) {
  62883. if (this.volumetricLightPostProcess) {
  62884. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  62885. }
  62886. this._volumetricLightStepsCount = count;
  62887. },
  62888. enumerable: true,
  62889. configurable: true
  62890. });
  62891. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  62892. get: function () {
  62893. return this._motionBlurSamples;
  62894. },
  62895. set: function (samples) {
  62896. if (this.motionBlurPostProcess) {
  62897. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  62898. }
  62899. this._motionBlurSamples = samples;
  62900. },
  62901. enumerable: true,
  62902. configurable: true
  62903. });
  62904. StandardRenderingPipeline.prototype._buildPipeline = function () {
  62905. var _this = this;
  62906. var ratio = this._ratio;
  62907. var scene = this._scene;
  62908. this._disposePostProcesses();
  62909. this._reset();
  62910. // Create pass post-process
  62911. if (!this._basePostProcess) {
  62912. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  62913. this.originalPostProcess.onApply = function (effect) {
  62914. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  62915. };
  62916. }
  62917. else {
  62918. this.originalPostProcess = this._basePostProcess;
  62919. }
  62920. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  62921. this._currentDepthOfFieldSource = this.originalPostProcess;
  62922. if (this._vlsEnabled) {
  62923. // Create volumetric light
  62924. this._createVolumetricLightPostProcess(scene, ratio);
  62925. // Create volumetric light final post-process
  62926. 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);
  62927. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  62928. }
  62929. if (this._bloomEnabled) {
  62930. // Create down sample X4 post-process
  62931. this._createDownSampleX4PostProcess(scene, ratio / 2);
  62932. // Create bright pass post-process
  62933. this._createBrightPassPostProcess(scene, ratio / 2);
  62934. // Create gaussian blur post-processes (down sampling blurs)
  62935. this._createBlurPostProcesses(scene, ratio / 4, 1);
  62936. // Create texture adder post-process
  62937. this._createTextureAdderPostProcess(scene, ratio);
  62938. // Create depth-of-field source post-process
  62939. 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);
  62940. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  62941. }
  62942. if (this._lensFlareEnabled) {
  62943. // Create lens flare post-process
  62944. this._createLensFlarePostProcess(scene, ratio);
  62945. // Create depth-of-field source post-process post lens-flare and disable it now
  62946. 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);
  62947. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  62948. }
  62949. if (this._hdrEnabled) {
  62950. // Create luminance
  62951. this._createLuminancePostProcesses(scene, this._floatTextureType);
  62952. // Create HDR
  62953. this._createHdrPostProcess(scene, ratio);
  62954. // Create depth-of-field source post-process post hdr and disable it now
  62955. 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);
  62956. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  62957. }
  62958. if (this._depthOfFieldEnabled) {
  62959. // Create gaussian blur used by depth-of-field
  62960. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  62961. // Create depth-of-field post-process
  62962. this._createDepthOfFieldPostProcess(scene, ratio);
  62963. }
  62964. if (this._motionBlurEnabled) {
  62965. // Create motion blur post-process
  62966. this._createMotionBlurPostProcess(scene, ratio);
  62967. }
  62968. if (this._cameras !== null) {
  62969. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  62970. }
  62971. };
  62972. // Down Sample X4 Post-Processs
  62973. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  62974. var _this = this;
  62975. var downSampleX4Offsets = new Array(32);
  62976. 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);
  62977. this.downSampleX4PostProcess.onApply = function (effect) {
  62978. var id = 0;
  62979. var width = _this.downSampleX4PostProcess.width;
  62980. var height = _this.downSampleX4PostProcess.height;
  62981. for (var i = -2; i < 2; i++) {
  62982. for (var j = -2; j < 2; j++) {
  62983. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  62984. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  62985. id += 2;
  62986. }
  62987. }
  62988. effect.setArray2("dsOffsets", downSampleX4Offsets);
  62989. };
  62990. // Add to pipeline
  62991. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  62992. };
  62993. // Brightpass Post-Process
  62994. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  62995. var _this = this;
  62996. var brightOffsets = new Array(8);
  62997. 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);
  62998. this.brightPassPostProcess.onApply = function (effect) {
  62999. var sU = (1.0 / _this.brightPassPostProcess.width);
  63000. var sV = (1.0 / _this.brightPassPostProcess.height);
  63001. brightOffsets[0] = -0.5 * sU;
  63002. brightOffsets[1] = 0.5 * sV;
  63003. brightOffsets[2] = 0.5 * sU;
  63004. brightOffsets[3] = 0.5 * sV;
  63005. brightOffsets[4] = -0.5 * sU;
  63006. brightOffsets[5] = -0.5 * sV;
  63007. brightOffsets[6] = 0.5 * sU;
  63008. brightOffsets[7] = -0.5 * sV;
  63009. effect.setArray2("dsOffsets", brightOffsets);
  63010. effect.setFloat("brightThreshold", _this.brightThreshold);
  63011. };
  63012. // Add to pipeline
  63013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63014. };
  63015. // Create blur H&V post-processes
  63016. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63017. var _this = this;
  63018. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63019. var engine = scene.getEngine();
  63020. 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);
  63021. 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);
  63022. blurX.onActivateObservable.add(function () {
  63023. var dw = blurX.width / engine.getRenderWidth();
  63024. blurX.kernel = _this[blurWidthKey] * dw;
  63025. });
  63026. blurY.onActivateObservable.add(function () {
  63027. var dw = blurY.height / engine.getRenderHeight();
  63028. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63029. });
  63030. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63032. this.blurHPostProcesses.push(blurX);
  63033. this.blurVPostProcesses.push(blurY);
  63034. };
  63035. // Create texture adder post-process
  63036. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63037. var _this = this;
  63038. 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);
  63039. this.textureAdderPostProcess.onApply = function (effect) {
  63040. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63041. effect.setTexture("lensSampler", _this.lensTexture);
  63042. effect.setFloat("exposure", _this.exposure);
  63043. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63044. };
  63045. // Add to pipeline
  63046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63047. };
  63048. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63049. var _this = this;
  63050. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63051. geometryRenderer.enablePosition = true;
  63052. var geometry = geometryRenderer.getGBuffer();
  63053. // Base post-process
  63054. 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));
  63055. var depthValues = BABYLON.Vector2.Zero();
  63056. this.volumetricLightPostProcess.onApply = function (effect) {
  63057. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63058. var generator = _this.sourceLight.getShadowGenerator();
  63059. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63060. effect.setTexture("positionSampler", geometry.textures[2]);
  63061. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63062. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63063. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63064. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63065. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63066. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63067. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63068. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63069. effect.setVector2("depthValues", depthValues);
  63070. }
  63071. };
  63072. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63073. // Smooth
  63074. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63075. // Merge
  63076. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63077. this.volumetricLightMergePostProces.onApply = function (effect) {
  63078. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63079. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63080. };
  63081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63082. };
  63083. // Create luminance
  63084. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63085. var _this = this;
  63086. // Create luminance
  63087. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63088. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63089. var offsets = [];
  63090. this.luminancePostProcess.onApply = function (effect) {
  63091. var sU = (1.0 / _this.luminancePostProcess.width);
  63092. var sV = (1.0 / _this.luminancePostProcess.height);
  63093. offsets[0] = -0.5 * sU;
  63094. offsets[1] = 0.5 * sV;
  63095. offsets[2] = 0.5 * sU;
  63096. offsets[3] = 0.5 * sV;
  63097. offsets[4] = -0.5 * sU;
  63098. offsets[5] = -0.5 * sV;
  63099. offsets[6] = 0.5 * sU;
  63100. offsets[7] = -0.5 * sV;
  63101. effect.setArray2("lumOffsets", offsets);
  63102. };
  63103. // Add to pipeline
  63104. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  63105. // Create down sample luminance
  63106. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  63107. var size = Math.pow(3, i);
  63108. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  63109. if (i === 0) {
  63110. defines += "#define FINAL_DOWN_SAMPLER";
  63111. }
  63112. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  63113. this.luminanceDownSamplePostProcesses.push(postProcess);
  63114. }
  63115. // Create callbacks and add effects
  63116. var lastLuminance = this.luminancePostProcess;
  63117. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  63118. var downSampleOffsets = new Array(18);
  63119. pp.onApply = function (effect) {
  63120. if (!lastLuminance) {
  63121. return;
  63122. }
  63123. var id = 0;
  63124. for (var x = -1; x < 2; x++) {
  63125. for (var y = -1; y < 2; y++) {
  63126. downSampleOffsets[id] = x / lastLuminance.width;
  63127. downSampleOffsets[id + 1] = y / lastLuminance.height;
  63128. id += 2;
  63129. }
  63130. }
  63131. effect.setArray2("dsOffsets", downSampleOffsets);
  63132. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  63133. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63134. lastLuminance = _this.luminancePostProcess;
  63135. }
  63136. else {
  63137. lastLuminance = pp;
  63138. }
  63139. };
  63140. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63141. pp.onAfterRender = function (effect) {
  63142. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  63143. 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);
  63144. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  63145. };
  63146. }
  63147. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  63148. });
  63149. };
  63150. // Create HDR post-process
  63151. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  63152. var _this = this;
  63153. 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);
  63154. var outputLiminance = 1;
  63155. var time = 0;
  63156. var lastTime = 0;
  63157. this.hdrPostProcess.onApply = function (effect) {
  63158. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  63159. time += scene.getEngine().getDeltaTime();
  63160. if (outputLiminance < 0) {
  63161. outputLiminance = _this._hdrCurrentLuminance;
  63162. }
  63163. else {
  63164. var dt = (lastTime - time) / 1000.0;
  63165. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  63166. outputLiminance += _this.hdrDecreaseRate * dt;
  63167. }
  63168. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  63169. outputLiminance -= _this.hdrIncreaseRate * dt;
  63170. }
  63171. else {
  63172. outputLiminance = _this._hdrCurrentLuminance;
  63173. }
  63174. }
  63175. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  63176. effect.setFloat("averageLuminance", outputLiminance);
  63177. lastTime = time;
  63178. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  63179. };
  63180. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  63181. };
  63182. // Create lens flare post-process
  63183. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63184. var _this = this;
  63185. 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);
  63186. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  63187. this._createBlurPostProcesses(scene, ratio / 4, 2);
  63188. 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);
  63189. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  63190. var resolution = new BABYLON.Vector2(0, 0);
  63191. // Lens flare
  63192. this.lensFlarePostProcess.onApply = function (effect) {
  63193. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  63194. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63195. effect.setFloat("strength", _this.lensFlareStrength);
  63196. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63197. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63198. // Shift
  63199. resolution.x = _this.lensFlarePostProcess.width;
  63200. resolution.y = _this.lensFlarePostProcess.height;
  63201. effect.setVector2("resolution", resolution);
  63202. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63203. };
  63204. // Compose
  63205. 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);
  63206. 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);
  63207. this.lensFlareComposePostProcess.onApply = function (effect) {
  63208. if (!_this._scene.activeCamera) {
  63209. return;
  63210. }
  63211. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63212. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63213. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63214. // Lens start rotation matrix
  63215. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  63216. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  63217. 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));
  63218. camRot *= 4.0;
  63219. 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);
  63220. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  63221. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  63222. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  63223. };
  63224. };
  63225. // Create depth-of-field post-process
  63226. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63227. var _this = this;
  63228. 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);
  63229. this.depthOfFieldPostProcess.onApply = function (effect) {
  63230. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63231. effect.setTexture("depthSampler", _this._getDepthTexture());
  63232. effect.setFloat("distance", _this.depthOfFieldDistance);
  63233. };
  63234. // Add to pipeline
  63235. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63236. };
  63237. // Create motion blur post-process
  63238. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  63239. var _this = this;
  63240. 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);
  63241. var motionScale = 0;
  63242. var prevViewProjection = BABYLON.Matrix.Identity();
  63243. var invViewProjection = BABYLON.Matrix.Identity();
  63244. var viewProjection = BABYLON.Matrix.Identity();
  63245. var screenSize = BABYLON.Vector2.Zero();
  63246. this.motionBlurPostProcess.onApply = function (effect) {
  63247. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  63248. viewProjection.invertToRef(invViewProjection);
  63249. effect.setMatrix("inverseViewProjection", invViewProjection);
  63250. effect.setMatrix("prevViewProjection", prevViewProjection);
  63251. prevViewProjection = viewProjection;
  63252. screenSize.x = _this.motionBlurPostProcess.width;
  63253. screenSize.y = _this.motionBlurPostProcess.height;
  63254. effect.setVector2("screenSize", screenSize);
  63255. motionScale = scene.getEngine().getFps() / 60.0;
  63256. effect.setFloat("motionScale", motionScale);
  63257. effect.setFloat("motionStrength", _this.motionStrength);
  63258. effect.setTexture("depthSampler", _this._getDepthTexture());
  63259. };
  63260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63261. };
  63262. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63263. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63264. var renderer = this._scene.enableGeometryBufferRenderer();
  63265. return renderer.getGBuffer().textures[0];
  63266. }
  63267. return this._scene.enableDepthRenderer().getDepthMap();
  63268. };
  63269. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  63270. for (var i = 0; i < this._cameras.length; i++) {
  63271. var camera = this._cameras[i];
  63272. if (this.originalPostProcess) {
  63273. this.originalPostProcess.dispose(camera);
  63274. }
  63275. if (this.downSampleX4PostProcess) {
  63276. this.downSampleX4PostProcess.dispose(camera);
  63277. }
  63278. if (this.brightPassPostProcess) {
  63279. this.brightPassPostProcess.dispose(camera);
  63280. }
  63281. if (this.textureAdderPostProcess) {
  63282. this.textureAdderPostProcess.dispose(camera);
  63283. }
  63284. if (this.textureAdderFinalPostProcess) {
  63285. this.textureAdderFinalPostProcess.dispose(camera);
  63286. }
  63287. if (this.volumetricLightPostProcess) {
  63288. this.volumetricLightPostProcess.dispose(camera);
  63289. }
  63290. if (this.volumetricLightSmoothXPostProcess) {
  63291. this.volumetricLightSmoothXPostProcess.dispose(camera);
  63292. }
  63293. if (this.volumetricLightSmoothYPostProcess) {
  63294. this.volumetricLightSmoothYPostProcess.dispose(camera);
  63295. }
  63296. if (this.volumetricLightMergePostProces) {
  63297. this.volumetricLightMergePostProces.dispose(camera);
  63298. }
  63299. if (this.volumetricLightFinalPostProcess) {
  63300. this.volumetricLightFinalPostProcess.dispose(camera);
  63301. }
  63302. if (this.lensFlarePostProcess) {
  63303. this.lensFlarePostProcess.dispose(camera);
  63304. }
  63305. if (this.lensFlareComposePostProcess) {
  63306. this.lensFlareComposePostProcess.dispose(camera);
  63307. }
  63308. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  63309. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  63310. }
  63311. if (this.luminancePostProcess) {
  63312. this.luminancePostProcess.dispose(camera);
  63313. }
  63314. if (this.hdrPostProcess) {
  63315. this.hdrPostProcess.dispose(camera);
  63316. }
  63317. if (this.hdrFinalPostProcess) {
  63318. this.hdrFinalPostProcess.dispose(camera);
  63319. }
  63320. if (this.depthOfFieldPostProcess) {
  63321. this.depthOfFieldPostProcess.dispose(camera);
  63322. }
  63323. if (this.motionBlurPostProcess) {
  63324. this.motionBlurPostProcess.dispose(camera);
  63325. }
  63326. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  63327. this.blurHPostProcesses[j].dispose(camera);
  63328. }
  63329. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  63330. this.blurVPostProcesses[j].dispose(camera);
  63331. }
  63332. }
  63333. this.originalPostProcess = null;
  63334. this.downSampleX4PostProcess = null;
  63335. this.brightPassPostProcess = null;
  63336. this.textureAdderPostProcess = null;
  63337. this.textureAdderFinalPostProcess = null;
  63338. this.volumetricLightPostProcess = null;
  63339. this.volumetricLightSmoothXPostProcess = null;
  63340. this.volumetricLightSmoothYPostProcess = null;
  63341. this.volumetricLightMergePostProces = null;
  63342. this.volumetricLightFinalPostProcess = null;
  63343. this.lensFlarePostProcess = null;
  63344. this.lensFlareComposePostProcess = null;
  63345. this.luminancePostProcess = null;
  63346. this.hdrPostProcess = null;
  63347. this.hdrFinalPostProcess = null;
  63348. this.depthOfFieldPostProcess = null;
  63349. this.motionBlurPostProcess = null;
  63350. this.luminanceDownSamplePostProcesses = [];
  63351. this.blurHPostProcesses = [];
  63352. this.blurVPostProcesses = [];
  63353. };
  63354. // Dispose
  63355. StandardRenderingPipeline.prototype.dispose = function () {
  63356. this._disposePostProcesses();
  63357. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63358. _super.prototype.dispose.call(this);
  63359. };
  63360. // Serialize rendering pipeline
  63361. StandardRenderingPipeline.prototype.serialize = function () {
  63362. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63363. serializationObject.customType = "StandardRenderingPipeline";
  63364. return serializationObject;
  63365. };
  63366. /**
  63367. * Static members
  63368. */
  63369. // Parse serialized pipeline
  63370. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63371. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  63372. };
  63373. // Luminance steps
  63374. StandardRenderingPipeline.LuminanceSteps = 6;
  63375. __decorate([
  63376. BABYLON.serialize()
  63377. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  63378. __decorate([
  63379. BABYLON.serialize()
  63380. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  63381. __decorate([
  63382. BABYLON.serialize()
  63383. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  63384. __decorate([
  63385. BABYLON.serialize()
  63386. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  63387. __decorate([
  63388. BABYLON.serializeAsTexture("lensTexture")
  63389. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  63390. __decorate([
  63391. BABYLON.serialize()
  63392. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  63393. __decorate([
  63394. BABYLON.serialize()
  63395. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  63396. __decorate([
  63397. BABYLON.serialize()
  63398. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  63399. __decorate([
  63400. BABYLON.serialize()
  63401. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  63402. __decorate([
  63403. BABYLON.serialize()
  63404. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  63405. __decorate([
  63406. BABYLON.serialize()
  63407. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  63408. __decorate([
  63409. BABYLON.serializeAsTexture("lensColorTexture")
  63410. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  63411. __decorate([
  63412. BABYLON.serialize()
  63413. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  63414. __decorate([
  63415. BABYLON.serialize()
  63416. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  63417. __decorate([
  63418. BABYLON.serialize()
  63419. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  63420. __decorate([
  63421. BABYLON.serialize()
  63422. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  63423. __decorate([
  63424. BABYLON.serializeAsTexture("lensStarTexture")
  63425. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  63426. __decorate([
  63427. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  63428. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  63429. __decorate([
  63430. BABYLON.serialize()
  63431. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  63432. __decorate([
  63433. BABYLON.serialize()
  63434. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63435. __decorate([
  63436. BABYLON.serialize()
  63437. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63438. __decorate([
  63439. BABYLON.serialize()
  63440. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63441. __decorate([
  63442. BABYLON.serialize()
  63443. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63444. __decorate([
  63445. BABYLON.serialize()
  63446. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63447. __decorate([
  63448. BABYLON.serialize()
  63449. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63450. __decorate([
  63451. BABYLON.serialize()
  63452. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63453. __decorate([
  63454. BABYLON.serialize()
  63455. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63456. __decorate([
  63457. BABYLON.serialize()
  63458. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63459. __decorate([
  63460. BABYLON.serialize()
  63461. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63462. __decorate([
  63463. BABYLON.serialize()
  63464. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63465. return StandardRenderingPipeline;
  63466. }(BABYLON.PostProcessRenderPipeline));
  63467. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63468. })(BABYLON || (BABYLON = {}));
  63469. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63470. var BABYLON;
  63471. (function (BABYLON) {
  63472. var FxaaPostProcess = /** @class */ (function (_super) {
  63473. __extends(FxaaPostProcess, _super);
  63474. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63475. if (camera === void 0) { camera = null; }
  63476. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63477. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63478. _this.onApplyObservable.add(function (effect) {
  63479. var texelSize = _this.texelSize;
  63480. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63481. });
  63482. return _this;
  63483. }
  63484. return FxaaPostProcess;
  63485. }(BABYLON.PostProcess));
  63486. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63487. })(BABYLON || (BABYLON = {}));
  63488. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63489. var BABYLON;
  63490. (function (BABYLON) {
  63491. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63492. __extends(DefaultRenderingPipeline, _super);
  63493. /**
  63494. * @constructor
  63495. * @param {string} name - The rendering pipeline name
  63496. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63497. * @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)
  63498. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63499. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63500. */
  63501. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63502. if (automaticBuild === void 0) { automaticBuild = true; }
  63503. var _this = _super.call(this, scene.getEngine(), name) || this;
  63504. _this.PassPostProcessId = "PassPostProcessEffect";
  63505. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63506. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63507. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63508. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63509. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63510. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63511. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63512. // IAnimatable
  63513. _this.animations = [];
  63514. // Values
  63515. _this._bloomEnabled = false;
  63516. _this._fxaaEnabled = false;
  63517. _this._imageProcessingEnabled = true;
  63518. _this._bloomScale = 0.6;
  63519. _this._buildAllowed = true;
  63520. /**
  63521. * Specifies the size of the bloom blur kernel, relative to the final output size
  63522. */
  63523. _this.bloomKernel = 64;
  63524. /**
  63525. * Specifies the weight of the bloom in the final rendering
  63526. */
  63527. _this._bloomWeight = 0.15;
  63528. _this._cameras = cameras || [];
  63529. _this._buildAllowed = automaticBuild;
  63530. // Initialize
  63531. _this._scene = scene;
  63532. var caps = _this._scene.getEngine().getCaps();
  63533. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63534. // Misc
  63535. if (_this._hdr) {
  63536. if (caps.textureHalfFloatRender) {
  63537. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63538. }
  63539. else if (caps.textureFloatRender) {
  63540. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63541. }
  63542. }
  63543. else {
  63544. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63545. }
  63546. // Attach
  63547. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63548. _this._buildPipeline();
  63549. return _this;
  63550. }
  63551. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63552. get: function () {
  63553. return this._bloomWeight;
  63554. },
  63555. set: function (value) {
  63556. if (this._bloomWeight === value) {
  63557. return;
  63558. }
  63559. this._bloomWeight = value;
  63560. if (this._hdr && this.copyBack) {
  63561. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63562. }
  63563. },
  63564. enumerable: true,
  63565. configurable: true
  63566. });
  63567. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63568. get: function () {
  63569. return this._bloomScale;
  63570. },
  63571. set: function (value) {
  63572. if (this._bloomScale === value) {
  63573. return;
  63574. }
  63575. this._bloomScale = value;
  63576. this._buildPipeline();
  63577. },
  63578. enumerable: true,
  63579. configurable: true
  63580. });
  63581. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63582. get: function () {
  63583. return this._bloomEnabled;
  63584. },
  63585. set: function (enabled) {
  63586. if (this._bloomEnabled === enabled) {
  63587. return;
  63588. }
  63589. this._bloomEnabled = enabled;
  63590. this._buildPipeline();
  63591. },
  63592. enumerable: true,
  63593. configurable: true
  63594. });
  63595. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63596. get: function () {
  63597. return this._fxaaEnabled;
  63598. },
  63599. set: function (enabled) {
  63600. if (this._fxaaEnabled === enabled) {
  63601. return;
  63602. }
  63603. this._fxaaEnabled = enabled;
  63604. this._buildPipeline();
  63605. },
  63606. enumerable: true,
  63607. configurable: true
  63608. });
  63609. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63610. get: function () {
  63611. return this._imageProcessingEnabled;
  63612. },
  63613. set: function (enabled) {
  63614. if (this._imageProcessingEnabled === enabled) {
  63615. return;
  63616. }
  63617. this._imageProcessingEnabled = enabled;
  63618. this._buildPipeline();
  63619. },
  63620. enumerable: true,
  63621. configurable: true
  63622. });
  63623. /**
  63624. * Force the compilation of the entire pipeline.
  63625. */
  63626. DefaultRenderingPipeline.prototype.prepare = function () {
  63627. var previousState = this._buildAllowed;
  63628. this._buildAllowed = true;
  63629. this._buildPipeline();
  63630. this._buildAllowed = previousState;
  63631. };
  63632. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63633. var _this = this;
  63634. if (!this._buildAllowed) {
  63635. return;
  63636. }
  63637. var engine = this._scene.getEngine();
  63638. this._disposePostProcesses();
  63639. this._reset();
  63640. if (this.bloomEnabled) {
  63641. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63642. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63643. if (!this._hdr) {
  63644. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63645. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63646. this.highlights.autoClear = false;
  63647. this.highlights.alwaysForcePOT = true;
  63648. }
  63649. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63650. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63651. this.blurX.alwaysForcePOT = true;
  63652. this.blurX.autoClear = false;
  63653. this.blurX.onActivateObservable.add(function () {
  63654. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63655. _this.blurX.kernel = _this.bloomKernel * dw;
  63656. });
  63657. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63658. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63659. this.blurY.alwaysForcePOT = true;
  63660. this.blurY.autoClear = false;
  63661. this.blurY.onActivateObservable.add(function () {
  63662. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63663. _this.blurY.kernel = _this.bloomKernel * dh;
  63664. });
  63665. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63666. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  63667. this.copyBack.alwaysForcePOT = true;
  63668. if (this._hdr) {
  63669. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  63670. var w = this.bloomWeight;
  63671. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  63672. }
  63673. else {
  63674. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  63675. }
  63676. this.copyBack.autoClear = false;
  63677. }
  63678. if (this._imageProcessingEnabled) {
  63679. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63680. if (this._hdr) {
  63681. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  63682. }
  63683. else {
  63684. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  63685. }
  63686. }
  63687. if (this.fxaaEnabled) {
  63688. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63689. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  63690. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63691. }
  63692. else if (this._hdr && this.imageProcessing) {
  63693. this.finalMerge = this.imageProcessing;
  63694. }
  63695. else {
  63696. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63697. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  63698. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63699. }
  63700. if (this.bloomEnabled) {
  63701. if (this._hdr) {
  63702. this.copyBack.shareOutputWith(this.blurX);
  63703. if (this.imageProcessing) {
  63704. this.imageProcessing.shareOutputWith(this.pass);
  63705. this.imageProcessing.autoClear = false;
  63706. }
  63707. else if (this.fxaa) {
  63708. this.fxaa.shareOutputWith(this.pass);
  63709. }
  63710. else {
  63711. this.finalMerge.shareOutputWith(this.pass);
  63712. }
  63713. }
  63714. else {
  63715. if (this.fxaa) {
  63716. this.fxaa.shareOutputWith(this.pass);
  63717. }
  63718. else {
  63719. this.finalMerge.shareOutputWith(this.pass);
  63720. }
  63721. }
  63722. }
  63723. if (this._cameras !== null) {
  63724. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63725. }
  63726. };
  63727. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  63728. for (var i = 0; i < this._cameras.length; i++) {
  63729. var camera = this._cameras[i];
  63730. if (this.pass) {
  63731. this.pass.dispose(camera);
  63732. }
  63733. if (this.highlights) {
  63734. this.highlights.dispose(camera);
  63735. }
  63736. if (this.blurX) {
  63737. this.blurX.dispose(camera);
  63738. }
  63739. if (this.blurY) {
  63740. this.blurY.dispose(camera);
  63741. }
  63742. if (this.copyBack) {
  63743. this.copyBack.dispose(camera);
  63744. }
  63745. if (this.imageProcessing) {
  63746. this.imageProcessing.dispose(camera);
  63747. }
  63748. if (this.fxaa) {
  63749. this.fxaa.dispose(camera);
  63750. }
  63751. if (this.finalMerge) {
  63752. this.finalMerge.dispose(camera);
  63753. }
  63754. }
  63755. this.pass = null;
  63756. this.highlights = null;
  63757. this.blurX = null;
  63758. this.blurY = null;
  63759. this.copyBack = null;
  63760. this.imageProcessing = null;
  63761. this.fxaa = null;
  63762. this.finalMerge = null;
  63763. };
  63764. // Dispose
  63765. DefaultRenderingPipeline.prototype.dispose = function () {
  63766. this._disposePostProcesses();
  63767. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63768. _super.prototype.dispose.call(this);
  63769. };
  63770. // Serialize rendering pipeline
  63771. DefaultRenderingPipeline.prototype.serialize = function () {
  63772. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63773. serializationObject.customType = "DefaultRenderingPipeline";
  63774. return serializationObject;
  63775. };
  63776. // Parse serialized pipeline
  63777. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63778. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  63779. };
  63780. __decorate([
  63781. BABYLON.serialize()
  63782. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  63783. __decorate([
  63784. BABYLON.serialize()
  63785. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  63786. __decorate([
  63787. BABYLON.serialize()
  63788. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  63789. __decorate([
  63790. BABYLON.serialize()
  63791. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  63792. __decorate([
  63793. BABYLON.serialize()
  63794. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  63795. __decorate([
  63796. BABYLON.serialize()
  63797. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  63798. __decorate([
  63799. BABYLON.serialize()
  63800. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  63801. __decorate([
  63802. BABYLON.serialize()
  63803. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  63804. return DefaultRenderingPipeline;
  63805. }(BABYLON.PostProcessRenderPipeline));
  63806. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  63807. })(BABYLON || (BABYLON = {}));
  63808. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  63809. var BABYLON;
  63810. (function (BABYLON) {
  63811. /**
  63812. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  63813. */
  63814. var GeometryBufferRenderer = /** @class */ (function () {
  63815. /**
  63816. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  63817. * @param scene The scene the buffer belongs to
  63818. * @param ratio How big is the buffer related to the main canvas.
  63819. */
  63820. function GeometryBufferRenderer(scene, ratio) {
  63821. if (ratio === void 0) { ratio = 1; }
  63822. this._enablePosition = false;
  63823. this._scene = scene;
  63824. this._ratio = ratio;
  63825. // Render target
  63826. this._createRenderTargets();
  63827. }
  63828. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  63829. /**
  63830. * Set the render list (meshes to be rendered) used in the G buffer.
  63831. */
  63832. set: function (meshes) {
  63833. this._multiRenderTarget.renderList = meshes;
  63834. },
  63835. enumerable: true,
  63836. configurable: true
  63837. });
  63838. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  63839. /**
  63840. * Gets wether or not G buffer are supported by the running hardware.
  63841. * This requires draw buffer supports
  63842. */
  63843. get: function () {
  63844. return this._multiRenderTarget.isSupported;
  63845. },
  63846. enumerable: true,
  63847. configurable: true
  63848. });
  63849. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  63850. /**
  63851. * Gets wether or not position are enabled for the G buffer.
  63852. */
  63853. get: function () {
  63854. return this._enablePosition;
  63855. },
  63856. /**
  63857. * Sets wether or not position are enabled for the G buffer.
  63858. */
  63859. set: function (enable) {
  63860. this._enablePosition = enable;
  63861. this.dispose();
  63862. this._createRenderTargets();
  63863. },
  63864. enumerable: true,
  63865. configurable: true
  63866. });
  63867. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  63868. /**
  63869. * Gets the scene associated with the buffer.
  63870. */
  63871. get: function () {
  63872. return this._scene;
  63873. },
  63874. enumerable: true,
  63875. configurable: true
  63876. });
  63877. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  63878. /**
  63879. * Gets the ratio used by the buffer during its creation.
  63880. * How big is the buffer related to the main canvas.
  63881. */
  63882. get: function () {
  63883. return this._ratio;
  63884. },
  63885. enumerable: true,
  63886. configurable: true
  63887. });
  63888. /**
  63889. * Checks wether everything is ready to render a submesh to the G buffer.
  63890. * @param subMesh the submesh to check readiness for
  63891. * @param useInstances is the mesh drawn using instance or not
  63892. * @returns true if ready otherwise false
  63893. */
  63894. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  63895. var material = subMesh.getMaterial();
  63896. if (material && material.disableDepthWrite) {
  63897. return false;
  63898. }
  63899. var defines = [];
  63900. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  63901. var mesh = subMesh.getMesh();
  63902. // Alpha test
  63903. if (material && material.needAlphaTesting()) {
  63904. defines.push("#define ALPHATEST");
  63905. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  63906. attribs.push(BABYLON.VertexBuffer.UVKind);
  63907. defines.push("#define UV1");
  63908. }
  63909. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  63910. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  63911. defines.push("#define UV2");
  63912. }
  63913. }
  63914. // Buffers
  63915. if (this._enablePosition) {
  63916. defines.push("#define POSITION");
  63917. }
  63918. // Bones
  63919. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  63920. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  63921. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  63922. if (mesh.numBoneInfluencers > 4) {
  63923. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  63924. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  63925. }
  63926. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  63927. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  63928. }
  63929. else {
  63930. defines.push("#define NUM_BONE_INFLUENCERS 0");
  63931. }
  63932. // Instances
  63933. if (useInstances) {
  63934. defines.push("#define INSTANCES");
  63935. attribs.push("world0");
  63936. attribs.push("world1");
  63937. attribs.push("world2");
  63938. attribs.push("world3");
  63939. }
  63940. // Get correct effect
  63941. var join = defines.join("\n");
  63942. if (this._cachedDefines !== join) {
  63943. this._cachedDefines = join;
  63944. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  63945. }
  63946. return this._effect.isReady();
  63947. };
  63948. /**
  63949. * Gets the current underlying G Buffer.
  63950. * @returns the buffer
  63951. */
  63952. GeometryBufferRenderer.prototype.getGBuffer = function () {
  63953. return this._multiRenderTarget;
  63954. };
  63955. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  63956. /**
  63957. * Gets the number of samples used to render the buffer (anti aliasing).
  63958. */
  63959. get: function () {
  63960. return this._multiRenderTarget.samples;
  63961. },
  63962. /**
  63963. * Sets the number of samples used to render the buffer (anti aliasing).
  63964. */
  63965. set: function (value) {
  63966. this._multiRenderTarget.samples = value;
  63967. },
  63968. enumerable: true,
  63969. configurable: true
  63970. });
  63971. /**
  63972. * Disposes the renderer and frees up associated resources.
  63973. */
  63974. GeometryBufferRenderer.prototype.dispose = function () {
  63975. this.getGBuffer().dispose();
  63976. };
  63977. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  63978. var _this = this;
  63979. var engine = this._scene.getEngine();
  63980. var count = this._enablePosition ? 3 : 2;
  63981. 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 });
  63982. if (!this.isSupported) {
  63983. return;
  63984. }
  63985. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63986. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63987. this._multiRenderTarget.refreshRate = 1;
  63988. this._multiRenderTarget.renderParticles = false;
  63989. this._multiRenderTarget.renderList = null;
  63990. // set default depth value to 1.0 (far away)
  63991. this._multiRenderTarget.onClearObservable.add(function (engine) {
  63992. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  63993. });
  63994. // Custom render function
  63995. var renderSubMesh = function (subMesh) {
  63996. var mesh = subMesh.getRenderingMesh();
  63997. var scene = _this._scene;
  63998. var engine = scene.getEngine();
  63999. var material = subMesh.getMaterial();
  64000. if (!material) {
  64001. return;
  64002. }
  64003. // Culling
  64004. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64005. // Managing instances
  64006. var batch = mesh._getInstancesRenderList(subMesh._id);
  64007. if (batch.mustReturn) {
  64008. return;
  64009. }
  64010. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64011. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  64012. engine.enableEffect(_this._effect);
  64013. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64014. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64015. _this._effect.setMatrix("view", scene.getViewMatrix());
  64016. // Alpha test
  64017. if (material && material.needAlphaTesting()) {
  64018. var alphaTexture = material.getAlphaTestTexture();
  64019. if (alphaTexture) {
  64020. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64021. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64022. }
  64023. }
  64024. // Bones
  64025. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64026. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64027. }
  64028. // Draw
  64029. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64030. }
  64031. };
  64032. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64033. var index;
  64034. if (depthOnlySubMeshes.length) {
  64035. engine.setColorWrite(false);
  64036. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64037. renderSubMesh(depthOnlySubMeshes.data[index]);
  64038. }
  64039. engine.setColorWrite(true);
  64040. }
  64041. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64042. renderSubMesh(opaqueSubMeshes.data[index]);
  64043. }
  64044. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64045. renderSubMesh(alphaTestSubMeshes.data[index]);
  64046. }
  64047. };
  64048. };
  64049. return GeometryBufferRenderer;
  64050. }());
  64051. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  64052. })(BABYLON || (BABYLON = {}));
  64053. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  64054. var BABYLON;
  64055. (function (BABYLON) {
  64056. var RefractionPostProcess = /** @class */ (function (_super) {
  64057. __extends(RefractionPostProcess, _super);
  64058. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  64059. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  64060. _this.color = color;
  64061. _this.depth = depth;
  64062. _this.colorLevel = colorLevel;
  64063. _this.onActivateObservable.add(function (cam) {
  64064. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  64065. });
  64066. _this.onApplyObservable.add(function (effect) {
  64067. effect.setColor3("baseColor", _this.color);
  64068. effect.setFloat("depth", _this.depth);
  64069. effect.setFloat("colorLevel", _this.colorLevel);
  64070. effect.setTexture("refractionSampler", _this._refRexture);
  64071. });
  64072. return _this;
  64073. }
  64074. // Methods
  64075. RefractionPostProcess.prototype.dispose = function (camera) {
  64076. if (this._refRexture) {
  64077. this._refRexture.dispose();
  64078. }
  64079. _super.prototype.dispose.call(this, camera);
  64080. };
  64081. return RefractionPostProcess;
  64082. }(BABYLON.PostProcess));
  64083. BABYLON.RefractionPostProcess = RefractionPostProcess;
  64084. })(BABYLON || (BABYLON = {}));
  64085. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  64086. var BABYLON;
  64087. (function (BABYLON) {
  64088. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  64089. __extends(BlackAndWhitePostProcess, _super);
  64090. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  64091. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  64092. _this.degree = 1;
  64093. _this.onApplyObservable.add(function (effect) {
  64094. effect.setFloat("degree", _this.degree);
  64095. });
  64096. return _this;
  64097. }
  64098. return BlackAndWhitePostProcess;
  64099. }(BABYLON.PostProcess));
  64100. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  64101. })(BABYLON || (BABYLON = {}));
  64102. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  64103. var BABYLON;
  64104. (function (BABYLON) {
  64105. var ConvolutionPostProcess = /** @class */ (function (_super) {
  64106. __extends(ConvolutionPostProcess, _super);
  64107. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  64108. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  64109. _this.kernel = kernel;
  64110. _this.onApply = function (effect) {
  64111. effect.setFloat2("screenSize", _this.width, _this.height);
  64112. effect.setArray("kernel", _this.kernel);
  64113. };
  64114. return _this;
  64115. }
  64116. // Statics
  64117. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  64118. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  64119. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  64120. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  64121. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  64122. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  64123. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  64124. return ConvolutionPostProcess;
  64125. }(BABYLON.PostProcess));
  64126. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  64127. })(BABYLON || (BABYLON = {}));
  64128. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  64129. var BABYLON;
  64130. (function (BABYLON) {
  64131. var FilterPostProcess = /** @class */ (function (_super) {
  64132. __extends(FilterPostProcess, _super);
  64133. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  64134. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  64135. _this.kernelMatrix = kernelMatrix;
  64136. _this.onApply = function (effect) {
  64137. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  64138. };
  64139. return _this;
  64140. }
  64141. return FilterPostProcess;
  64142. }(BABYLON.PostProcess));
  64143. BABYLON.FilterPostProcess = FilterPostProcess;
  64144. })(BABYLON || (BABYLON = {}));
  64145. //# sourceMappingURL=babylon.filterPostProcess.js.map
  64146. var BABYLON;
  64147. (function (BABYLON) {
  64148. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  64149. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  64150. __extends(VolumetricLightScatteringPostProcess, _super);
  64151. /**
  64152. * @constructor
  64153. * @param {string} name - The post-process name
  64154. * @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)
  64155. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  64156. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  64157. * @param {number} samples - The post-process quality, default 100
  64158. * @param {number} samplingMode - The post-process filtering mode
  64159. * @param {BABYLON.Engine} engine - The babylon engine
  64160. * @param {boolean} reusable - If the post-process is reusable
  64161. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  64162. */
  64163. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  64164. if (samples === void 0) { samples = 100; }
  64165. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64166. 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;
  64167. _this._screenCoordinates = BABYLON.Vector2.Zero();
  64168. /**
  64169. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  64170. * @type {Vector3}
  64171. */
  64172. _this.customMeshPosition = BABYLON.Vector3.Zero();
  64173. /**
  64174. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  64175. * @type {boolean}
  64176. */
  64177. _this.useCustomMeshPosition = false;
  64178. /**
  64179. * If the post-process should inverse the light scattering direction
  64180. * @type {boolean}
  64181. */
  64182. _this.invert = true;
  64183. /**
  64184. * Array containing the excluded meshes not rendered in the internal pass
  64185. */
  64186. _this.excludedMeshes = new Array();
  64187. /**
  64188. * Controls the overall intensity of the post-process
  64189. * @type {number}
  64190. */
  64191. _this.exposure = 0.3;
  64192. /**
  64193. * Dissipates each sample's contribution in range [0, 1]
  64194. * @type {number}
  64195. */
  64196. _this.decay = 0.96815;
  64197. /**
  64198. * Controls the overall intensity of each sample
  64199. * @type {number}
  64200. */
  64201. _this.weight = 0.58767;
  64202. /**
  64203. * Controls the density of each sample
  64204. * @type {number}
  64205. */
  64206. _this.density = 0.926;
  64207. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  64208. engine = scene.getEngine();
  64209. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  64210. // Configure mesh
  64211. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  64212. // Configure
  64213. _this._createPass(scene, ratio.passRatio || ratio);
  64214. _this.onActivate = function (camera) {
  64215. if (!_this.isSupported) {
  64216. _this.dispose(camera);
  64217. }
  64218. _this.onActivate = null;
  64219. };
  64220. _this.onApplyObservable.add(function (effect) {
  64221. _this._updateMeshScreenCoordinates(scene);
  64222. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  64223. effect.setFloat("exposure", _this.exposure);
  64224. effect.setFloat("decay", _this.decay);
  64225. effect.setFloat("weight", _this.weight);
  64226. effect.setFloat("density", _this.density);
  64227. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  64228. });
  64229. return _this;
  64230. }
  64231. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  64232. get: function () {
  64233. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64234. return false;
  64235. },
  64236. set: function (useDiffuseColor) {
  64237. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64238. },
  64239. enumerable: true,
  64240. configurable: true
  64241. });
  64242. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  64243. return "VolumetricLightScatteringPostProcess";
  64244. };
  64245. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  64246. var mesh = subMesh.getMesh();
  64247. // Render this.mesh as default
  64248. if (mesh === this.mesh && mesh.material) {
  64249. return mesh.material.isReady(mesh);
  64250. }
  64251. var defines = [];
  64252. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64253. var material = subMesh.getMaterial();
  64254. // Alpha test
  64255. if (material) {
  64256. if (material.needAlphaTesting()) {
  64257. defines.push("#define ALPHATEST");
  64258. }
  64259. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64260. attribs.push(BABYLON.VertexBuffer.UVKind);
  64261. defines.push("#define UV1");
  64262. }
  64263. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64264. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64265. defines.push("#define UV2");
  64266. }
  64267. }
  64268. // Bones
  64269. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64270. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64271. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64272. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64273. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  64274. }
  64275. else {
  64276. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64277. }
  64278. // Instances
  64279. if (useInstances) {
  64280. defines.push("#define INSTANCES");
  64281. attribs.push("world0");
  64282. attribs.push("world1");
  64283. attribs.push("world2");
  64284. attribs.push("world3");
  64285. }
  64286. // Get correct effect
  64287. var join = defines.join("\n");
  64288. if (this._cachedDefines !== join) {
  64289. this._cachedDefines = join;
  64290. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  64291. }
  64292. return this._volumetricLightScatteringPass.isReady();
  64293. };
  64294. /**
  64295. * Sets the new light position for light scattering effect
  64296. * @param {BABYLON.Vector3} The new custom light position
  64297. */
  64298. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  64299. this.customMeshPosition = position;
  64300. };
  64301. /**
  64302. * Returns the light position for light scattering effect
  64303. * @return {BABYLON.Vector3} The custom light position
  64304. */
  64305. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  64306. return this.customMeshPosition;
  64307. };
  64308. /**
  64309. * Disposes the internal assets and detaches the post-process from the camera
  64310. */
  64311. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  64312. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  64313. if (rttIndex !== -1) {
  64314. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  64315. }
  64316. this._volumetricLightScatteringRTT.dispose();
  64317. _super.prototype.dispose.call(this, camera);
  64318. };
  64319. /**
  64320. * Returns the render target texture used by the post-process
  64321. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  64322. */
  64323. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  64324. return this._volumetricLightScatteringRTT;
  64325. };
  64326. // Private methods
  64327. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  64328. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  64329. return true;
  64330. }
  64331. return false;
  64332. };
  64333. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  64334. var _this = this;
  64335. var engine = scene.getEngine();
  64336. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64337. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64338. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64339. this._volumetricLightScatteringRTT.renderList = null;
  64340. this._volumetricLightScatteringRTT.renderParticles = false;
  64341. var camera = this.getCamera();
  64342. if (camera) {
  64343. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64344. }
  64345. else {
  64346. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64347. }
  64348. // Custom render function for submeshes
  64349. var renderSubMesh = function (subMesh) {
  64350. var mesh = subMesh.getRenderingMesh();
  64351. if (_this._meshExcluded(mesh)) {
  64352. return;
  64353. }
  64354. var material = subMesh.getMaterial();
  64355. if (!material) {
  64356. return;
  64357. }
  64358. var scene = mesh.getScene();
  64359. var engine = scene.getEngine();
  64360. // Culling
  64361. engine.setState(material.backFaceCulling);
  64362. // Managing instances
  64363. var batch = mesh._getInstancesRenderList(subMesh._id);
  64364. if (batch.mustReturn) {
  64365. return;
  64366. }
  64367. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64368. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  64369. var effect = _this._volumetricLightScatteringPass;
  64370. if (mesh === _this.mesh) {
  64371. if (subMesh.effect) {
  64372. effect = subMesh.effect;
  64373. }
  64374. else {
  64375. effect = material.getEffect();
  64376. }
  64377. }
  64378. engine.enableEffect(effect);
  64379. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  64380. if (mesh === _this.mesh) {
  64381. material.bind(mesh.getWorldMatrix(), mesh);
  64382. }
  64383. else {
  64384. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  64385. // Alpha test
  64386. if (material && material.needAlphaTesting()) {
  64387. var alphaTexture = material.getAlphaTestTexture();
  64388. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  64389. if (alphaTexture) {
  64390. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64391. }
  64392. }
  64393. // Bones
  64394. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64395. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64396. }
  64397. }
  64398. // Draw
  64399. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  64400. }
  64401. };
  64402. // Render target texture callbacks
  64403. var savedSceneClearColor;
  64404. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  64405. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  64406. savedSceneClearColor = scene.clearColor;
  64407. scene.clearColor = sceneClearColor;
  64408. });
  64409. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  64410. scene.clearColor = savedSceneClearColor;
  64411. });
  64412. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64413. var engine = scene.getEngine();
  64414. var index;
  64415. if (depthOnlySubMeshes.length) {
  64416. engine.setColorWrite(false);
  64417. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64418. renderSubMesh(depthOnlySubMeshes.data[index]);
  64419. }
  64420. engine.setColorWrite(true);
  64421. }
  64422. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64423. renderSubMesh(opaqueSubMeshes.data[index]);
  64424. }
  64425. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64426. renderSubMesh(alphaTestSubMeshes.data[index]);
  64427. }
  64428. if (transparentSubMeshes.length) {
  64429. // Sort sub meshes
  64430. for (index = 0; index < transparentSubMeshes.length; index++) {
  64431. var submesh = transparentSubMeshes.data[index];
  64432. var boundingInfo = submesh.getBoundingInfo();
  64433. if (boundingInfo && scene.activeCamera) {
  64434. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64435. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64436. }
  64437. }
  64438. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64439. sortedArray.sort(function (a, b) {
  64440. // Alpha index first
  64441. if (a._alphaIndex > b._alphaIndex) {
  64442. return 1;
  64443. }
  64444. if (a._alphaIndex < b._alphaIndex) {
  64445. return -1;
  64446. }
  64447. // Then distance to camera
  64448. if (a._distanceToCamera < b._distanceToCamera) {
  64449. return 1;
  64450. }
  64451. if (a._distanceToCamera > b._distanceToCamera) {
  64452. return -1;
  64453. }
  64454. return 0;
  64455. });
  64456. // Render sub meshes
  64457. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64458. for (index = 0; index < sortedArray.length; index++) {
  64459. renderSubMesh(sortedArray[index]);
  64460. }
  64461. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64462. }
  64463. };
  64464. };
  64465. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64466. var transform = scene.getTransformMatrix();
  64467. var meshPosition;
  64468. if (this.useCustomMeshPosition) {
  64469. meshPosition = this.customMeshPosition;
  64470. }
  64471. else if (this.attachedNode) {
  64472. meshPosition = this.attachedNode.position;
  64473. }
  64474. else {
  64475. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64476. }
  64477. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64478. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64479. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64480. if (this.invert)
  64481. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64482. };
  64483. // Static methods
  64484. /**
  64485. * Creates a default mesh for the Volumeric Light Scattering post-process
  64486. * @param {string} The mesh name
  64487. * @param {BABYLON.Scene} The scene where to create the mesh
  64488. * @return {BABYLON.Mesh} the default mesh
  64489. */
  64490. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64491. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64492. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64493. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64494. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64495. mesh.material = material;
  64496. return mesh;
  64497. };
  64498. __decorate([
  64499. BABYLON.serializeAsVector3()
  64500. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64501. __decorate([
  64502. BABYLON.serialize()
  64503. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64504. __decorate([
  64505. BABYLON.serialize()
  64506. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64507. __decorate([
  64508. BABYLON.serializeAsMeshReference()
  64509. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64510. __decorate([
  64511. BABYLON.serialize()
  64512. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64513. __decorate([
  64514. BABYLON.serialize()
  64515. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64516. __decorate([
  64517. BABYLON.serialize()
  64518. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64519. __decorate([
  64520. BABYLON.serialize()
  64521. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64522. __decorate([
  64523. BABYLON.serialize()
  64524. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64525. return VolumetricLightScatteringPostProcess;
  64526. }(BABYLON.PostProcess));
  64527. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64528. })(BABYLON || (BABYLON = {}));
  64529. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64530. //
  64531. // This post-process allows the modification of rendered colors by using
  64532. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64533. //
  64534. // The object needs to be provided an url to a texture containing the color
  64535. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64536. // Use an image editing software to tweak the LUT to match your needs.
  64537. //
  64538. // For an example of a color LUT, see here:
  64539. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64540. // For explanations on color grading, see here:
  64541. // http://udn.epicgames.com/Three/ColorGrading.html
  64542. //
  64543. var BABYLON;
  64544. (function (BABYLON) {
  64545. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64546. __extends(ColorCorrectionPostProcess, _super);
  64547. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64548. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64549. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64550. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64551. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64552. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64553. _this.onApply = function (effect) {
  64554. effect.setTexture("colorTable", _this._colorTableTexture);
  64555. };
  64556. return _this;
  64557. }
  64558. return ColorCorrectionPostProcess;
  64559. }(BABYLON.PostProcess));
  64560. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64561. })(BABYLON || (BABYLON = {}));
  64562. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64563. var BABYLON;
  64564. (function (BABYLON) {
  64565. var TonemappingOperator;
  64566. (function (TonemappingOperator) {
  64567. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64568. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64569. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64570. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64571. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64572. ;
  64573. var TonemapPostProcess = /** @class */ (function (_super) {
  64574. __extends(TonemapPostProcess, _super);
  64575. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64576. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64577. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64578. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64579. _this._operator = _operator;
  64580. _this.exposureAdjustment = exposureAdjustment;
  64581. var defines = "#define ";
  64582. if (_this._operator === TonemappingOperator.Hable)
  64583. defines += "HABLE_TONEMAPPING";
  64584. else if (_this._operator === TonemappingOperator.Reinhard)
  64585. defines += "REINHARD_TONEMAPPING";
  64586. else if (_this._operator === TonemappingOperator.HejiDawson)
  64587. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64588. else if (_this._operator === TonemappingOperator.Photographic)
  64589. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64590. //sadly a second call to create the effect.
  64591. _this.updateEffect(defines);
  64592. _this.onApply = function (effect) {
  64593. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64594. };
  64595. return _this;
  64596. }
  64597. return TonemapPostProcess;
  64598. }(BABYLON.PostProcess));
  64599. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64600. })(BABYLON || (BABYLON = {}));
  64601. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64602. var BABYLON;
  64603. (function (BABYLON) {
  64604. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64605. __extends(DisplayPassPostProcess, _super);
  64606. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64607. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64608. }
  64609. return DisplayPassPostProcess;
  64610. }(BABYLON.PostProcess));
  64611. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64612. })(BABYLON || (BABYLON = {}));
  64613. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64614. var BABYLON;
  64615. (function (BABYLON) {
  64616. var HighlightsPostProcess = /** @class */ (function (_super) {
  64617. __extends(HighlightsPostProcess, _super);
  64618. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64619. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64620. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64621. }
  64622. return HighlightsPostProcess;
  64623. }(BABYLON.PostProcess));
  64624. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64625. })(BABYLON || (BABYLON = {}));
  64626. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64627. var BABYLON;
  64628. (function (BABYLON) {
  64629. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64630. __extends(ImageProcessingPostProcess, _super);
  64631. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64632. if (camera === void 0) { camera = null; }
  64633. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64634. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64635. _this._fromLinearSpace = true;
  64636. /**
  64637. * Defines cache preventing GC.
  64638. */
  64639. _this._defines = {
  64640. IMAGEPROCESSING: false,
  64641. VIGNETTE: false,
  64642. VIGNETTEBLENDMODEMULTIPLY: false,
  64643. VIGNETTEBLENDMODEOPAQUE: false,
  64644. TONEMAPPING: false,
  64645. CONTRAST: false,
  64646. COLORCURVES: false,
  64647. COLORGRADING: false,
  64648. COLORGRADING3D: false,
  64649. FROMLINEARSPACE: false,
  64650. SAMPLER3DGREENDEPTH: false,
  64651. SAMPLER3DBGRMAP: false,
  64652. IMAGEPROCESSINGPOSTPROCESS: false,
  64653. EXPOSURE: false,
  64654. };
  64655. // Setup the configuration as forced by the constructor. This would then not force the
  64656. // scene materials output in linear space and let untouched the default forward pass.
  64657. if (imageProcessingConfiguration) {
  64658. imageProcessingConfiguration.applyByPostProcess = true;
  64659. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64660. // This will cause the shader to be compiled
  64661. _this.fromLinearSpace = false;
  64662. }
  64663. else {
  64664. _this._attachImageProcessingConfiguration(null, true);
  64665. _this.imageProcessingConfiguration.applyByPostProcess = true;
  64666. }
  64667. _this.onApply = function (effect) {
  64668. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  64669. };
  64670. return _this;
  64671. }
  64672. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  64673. /**
  64674. * Gets the image processing configuration used either in this material.
  64675. */
  64676. get: function () {
  64677. return this._imageProcessingConfiguration;
  64678. },
  64679. /**
  64680. * Sets the Default image processing configuration used either in the this material.
  64681. *
  64682. * If sets to null, the scene one is in use.
  64683. */
  64684. set: function (value) {
  64685. this._attachImageProcessingConfiguration(value);
  64686. },
  64687. enumerable: true,
  64688. configurable: true
  64689. });
  64690. /**
  64691. * Attaches a new image processing configuration to the PBR Material.
  64692. * @param configuration
  64693. */
  64694. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  64695. var _this = this;
  64696. if (doNotBuild === void 0) { doNotBuild = false; }
  64697. if (configuration === this._imageProcessingConfiguration) {
  64698. return;
  64699. }
  64700. // Detaches observer.
  64701. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64702. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64703. }
  64704. // Pick the scene configuration if needed.
  64705. if (!configuration) {
  64706. var scene = null;
  64707. var engine = this.getEngine();
  64708. var camera = this.getCamera();
  64709. if (camera) {
  64710. scene = camera.getScene();
  64711. }
  64712. else if (engine && engine.scenes) {
  64713. var scenes = engine.scenes;
  64714. scene = scenes[scenes.length - 1];
  64715. }
  64716. else {
  64717. scene = BABYLON.Engine.LastCreatedScene;
  64718. }
  64719. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  64720. }
  64721. else {
  64722. this._imageProcessingConfiguration = configuration;
  64723. }
  64724. // Attaches observer.
  64725. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  64726. _this._updateParameters();
  64727. });
  64728. // Ensure the effect will be rebuilt.
  64729. if (!doNotBuild) {
  64730. this._updateParameters();
  64731. }
  64732. };
  64733. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  64734. /**
  64735. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64736. */
  64737. get: function () {
  64738. return this.imageProcessingConfiguration.colorCurves;
  64739. },
  64740. /**
  64741. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64742. */
  64743. set: function (value) {
  64744. this.imageProcessingConfiguration.colorCurves = value;
  64745. },
  64746. enumerable: true,
  64747. configurable: true
  64748. });
  64749. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  64750. /**
  64751. * Gets wether the color curves effect is enabled.
  64752. */
  64753. get: function () {
  64754. return this.imageProcessingConfiguration.colorCurvesEnabled;
  64755. },
  64756. /**
  64757. * Sets wether the color curves effect is enabled.
  64758. */
  64759. set: function (value) {
  64760. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  64761. },
  64762. enumerable: true,
  64763. configurable: true
  64764. });
  64765. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  64766. /**
  64767. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64768. */
  64769. get: function () {
  64770. return this.imageProcessingConfiguration.colorGradingTexture;
  64771. },
  64772. /**
  64773. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64774. */
  64775. set: function (value) {
  64776. this.imageProcessingConfiguration.colorGradingTexture = value;
  64777. },
  64778. enumerable: true,
  64779. configurable: true
  64780. });
  64781. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  64782. /**
  64783. * Gets wether the color grading effect is enabled.
  64784. */
  64785. get: function () {
  64786. return this.imageProcessingConfiguration.colorGradingEnabled;
  64787. },
  64788. /**
  64789. * Gets wether the color grading effect is enabled.
  64790. */
  64791. set: function (value) {
  64792. this.imageProcessingConfiguration.colorGradingEnabled = value;
  64793. },
  64794. enumerable: true,
  64795. configurable: true
  64796. });
  64797. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  64798. /**
  64799. * Gets exposure used in the effect.
  64800. */
  64801. get: function () {
  64802. return this.imageProcessingConfiguration.exposure;
  64803. },
  64804. /**
  64805. * Sets exposure used in the effect.
  64806. */
  64807. set: function (value) {
  64808. this.imageProcessingConfiguration.exposure = value;
  64809. },
  64810. enumerable: true,
  64811. configurable: true
  64812. });
  64813. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  64814. /**
  64815. * Gets wether tonemapping is enabled or not.
  64816. */
  64817. get: function () {
  64818. return this._imageProcessingConfiguration.toneMappingEnabled;
  64819. },
  64820. /**
  64821. * Sets wether tonemapping is enabled or not
  64822. */
  64823. set: function (value) {
  64824. this._imageProcessingConfiguration.toneMappingEnabled = value;
  64825. },
  64826. enumerable: true,
  64827. configurable: true
  64828. });
  64829. ;
  64830. ;
  64831. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  64832. /**
  64833. * Gets contrast used in the effect.
  64834. */
  64835. get: function () {
  64836. return this.imageProcessingConfiguration.contrast;
  64837. },
  64838. /**
  64839. * Sets contrast used in the effect.
  64840. */
  64841. set: function (value) {
  64842. this.imageProcessingConfiguration.contrast = value;
  64843. },
  64844. enumerable: true,
  64845. configurable: true
  64846. });
  64847. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  64848. /**
  64849. * Gets Vignette stretch size.
  64850. */
  64851. get: function () {
  64852. return this.imageProcessingConfiguration.vignetteStretch;
  64853. },
  64854. /**
  64855. * Sets Vignette stretch size.
  64856. */
  64857. set: function (value) {
  64858. this.imageProcessingConfiguration.vignetteStretch = value;
  64859. },
  64860. enumerable: true,
  64861. configurable: true
  64862. });
  64863. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  64864. /**
  64865. * Gets Vignette centre X Offset.
  64866. */
  64867. get: function () {
  64868. return this.imageProcessingConfiguration.vignetteCentreX;
  64869. },
  64870. /**
  64871. * Sets Vignette centre X Offset.
  64872. */
  64873. set: function (value) {
  64874. this.imageProcessingConfiguration.vignetteCentreX = value;
  64875. },
  64876. enumerable: true,
  64877. configurable: true
  64878. });
  64879. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  64880. /**
  64881. * Gets Vignette centre Y Offset.
  64882. */
  64883. get: function () {
  64884. return this.imageProcessingConfiguration.vignetteCentreY;
  64885. },
  64886. /**
  64887. * Sets Vignette centre Y Offset.
  64888. */
  64889. set: function (value) {
  64890. this.imageProcessingConfiguration.vignetteCentreY = value;
  64891. },
  64892. enumerable: true,
  64893. configurable: true
  64894. });
  64895. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  64896. /**
  64897. * Gets Vignette weight or intensity of the vignette effect.
  64898. */
  64899. get: function () {
  64900. return this.imageProcessingConfiguration.vignetteWeight;
  64901. },
  64902. /**
  64903. * Sets Vignette weight or intensity of the vignette effect.
  64904. */
  64905. set: function (value) {
  64906. this.imageProcessingConfiguration.vignetteWeight = value;
  64907. },
  64908. enumerable: true,
  64909. configurable: true
  64910. });
  64911. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  64912. /**
  64913. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64914. * if vignetteEnabled is set to true.
  64915. */
  64916. get: function () {
  64917. return this.imageProcessingConfiguration.vignetteColor;
  64918. },
  64919. /**
  64920. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  64921. * if vignetteEnabled is set to true.
  64922. */
  64923. set: function (value) {
  64924. this.imageProcessingConfiguration.vignetteColor = value;
  64925. },
  64926. enumerable: true,
  64927. configurable: true
  64928. });
  64929. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  64930. /**
  64931. * Gets Camera field of view used by the Vignette effect.
  64932. */
  64933. get: function () {
  64934. return this.imageProcessingConfiguration.vignetteCameraFov;
  64935. },
  64936. /**
  64937. * Sets Camera field of view used by the Vignette effect.
  64938. */
  64939. set: function (value) {
  64940. this.imageProcessingConfiguration.vignetteCameraFov = value;
  64941. },
  64942. enumerable: true,
  64943. configurable: true
  64944. });
  64945. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  64946. /**
  64947. * Gets the vignette blend mode allowing different kind of effect.
  64948. */
  64949. get: function () {
  64950. return this.imageProcessingConfiguration.vignetteBlendMode;
  64951. },
  64952. /**
  64953. * Sets the vignette blend mode allowing different kind of effect.
  64954. */
  64955. set: function (value) {
  64956. this.imageProcessingConfiguration.vignetteBlendMode = value;
  64957. },
  64958. enumerable: true,
  64959. configurable: true
  64960. });
  64961. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  64962. /**
  64963. * Gets wether the vignette effect is enabled.
  64964. */
  64965. get: function () {
  64966. return this.imageProcessingConfiguration.vignetteEnabled;
  64967. },
  64968. /**
  64969. * Sets wether the vignette effect is enabled.
  64970. */
  64971. set: function (value) {
  64972. this.imageProcessingConfiguration.vignetteEnabled = value;
  64973. },
  64974. enumerable: true,
  64975. configurable: true
  64976. });
  64977. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  64978. /**
  64979. * Gets wether the input of the processing is in Gamma or Linear Space.
  64980. */
  64981. get: function () {
  64982. return this._fromLinearSpace;
  64983. },
  64984. /**
  64985. * Sets wether the input of the processing is in Gamma or Linear Space.
  64986. */
  64987. set: function (value) {
  64988. if (this._fromLinearSpace === value) {
  64989. return;
  64990. }
  64991. this._fromLinearSpace = value;
  64992. this._updateParameters();
  64993. },
  64994. enumerable: true,
  64995. configurable: true
  64996. });
  64997. ImageProcessingPostProcess.prototype.getClassName = function () {
  64998. return "ImageProcessingPostProcess";
  64999. };
  65000. ImageProcessingPostProcess.prototype._updateParameters = function () {
  65001. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  65002. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  65003. var defines = "";
  65004. for (var define in this._defines) {
  65005. if (this._defines[define]) {
  65006. defines += "#define " + define + ";\r\n";
  65007. }
  65008. }
  65009. var samplers = ["textureSampler"];
  65010. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  65011. var uniforms = ["scale"];
  65012. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  65013. this.updateEffect(defines, uniforms, samplers);
  65014. };
  65015. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  65016. _super.prototype.dispose.call(this, camera);
  65017. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65018. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65019. }
  65020. this.imageProcessingConfiguration.applyByPostProcess = false;
  65021. };
  65022. __decorate([
  65023. BABYLON.serialize()
  65024. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  65025. return ImageProcessingPostProcess;
  65026. }(BABYLON.PostProcess));
  65027. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  65028. })(BABYLON || (BABYLON = {}));
  65029. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  65030. var BABYLON;
  65031. (function (BABYLON) {
  65032. var BlurPostProcess = /** @class */ (function (_super) {
  65033. __extends(BlurPostProcess, _super);
  65034. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  65035. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65036. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65037. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  65038. _this.direction = direction;
  65039. _this._packedFloat = false;
  65040. _this.onApplyObservable.add(function (effect) {
  65041. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  65042. });
  65043. _this.kernel = kernel;
  65044. return _this;
  65045. }
  65046. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  65047. /**
  65048. * Gets the length in pixels of the blur sample region
  65049. */
  65050. get: function () {
  65051. return this._idealKernel;
  65052. },
  65053. /**
  65054. * Sets the length in pixels of the blur sample region
  65055. */
  65056. set: function (v) {
  65057. if (this._idealKernel === v) {
  65058. return;
  65059. }
  65060. v = Math.max(v, 1);
  65061. this._idealKernel = v;
  65062. this._kernel = this._nearestBestKernel(v);
  65063. this._updateParameters();
  65064. },
  65065. enumerable: true,
  65066. configurable: true
  65067. });
  65068. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  65069. /**
  65070. * Gets wether or not the blur is unpacking/repacking floats
  65071. */
  65072. get: function () {
  65073. return this._packedFloat;
  65074. },
  65075. /**
  65076. * Sets wether or not the blur needs to unpack/repack floats
  65077. */
  65078. set: function (v) {
  65079. if (this._packedFloat === v) {
  65080. return;
  65081. }
  65082. this._packedFloat = v;
  65083. this._updateParameters();
  65084. },
  65085. enumerable: true,
  65086. configurable: true
  65087. });
  65088. BlurPostProcess.prototype._updateParameters = function () {
  65089. // Generate sampling offsets and weights
  65090. var N = this._kernel;
  65091. var centerIndex = (N - 1) / 2;
  65092. // Generate Gaussian sampling weights over kernel
  65093. var offsets = [];
  65094. var weights = [];
  65095. var totalWeight = 0;
  65096. for (var i = 0; i < N; i++) {
  65097. var u = i / (N - 1);
  65098. var w = this._gaussianWeight(u * 2.0 - 1);
  65099. offsets[i] = (i - centerIndex);
  65100. weights[i] = w;
  65101. totalWeight += w;
  65102. }
  65103. // Normalize weights
  65104. for (var i = 0; i < weights.length; i++) {
  65105. weights[i] /= totalWeight;
  65106. }
  65107. // Optimize: combine samples to take advantage of hardware linear sampling
  65108. // Walk from left to center, combining pairs (symmetrically)
  65109. var linearSamplingWeights = [];
  65110. var linearSamplingOffsets = [];
  65111. var linearSamplingMap = [];
  65112. for (var i = 0; i <= centerIndex; i += 2) {
  65113. var j = Math.min(i + 1, Math.floor(centerIndex));
  65114. var singleCenterSample = i === j;
  65115. if (singleCenterSample) {
  65116. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65117. }
  65118. else {
  65119. var sharedCell = j === centerIndex;
  65120. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  65121. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  65122. if (offsetLinear === 0) {
  65123. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65124. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  65125. }
  65126. else {
  65127. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  65128. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  65129. }
  65130. }
  65131. }
  65132. for (var i = 0; i < linearSamplingMap.length; i++) {
  65133. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  65134. linearSamplingWeights[i] = linearSamplingMap[i].w;
  65135. }
  65136. // Replace with optimized
  65137. offsets = linearSamplingOffsets;
  65138. weights = linearSamplingWeights;
  65139. // Generate shaders
  65140. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  65141. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  65142. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  65143. var defines = "";
  65144. for (var i = 0; i < varyingCount; i++) {
  65145. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  65146. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  65147. }
  65148. var depCount = 0;
  65149. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  65150. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  65151. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  65152. depCount++;
  65153. }
  65154. if (this.packedFloat) {
  65155. defines += "#define PACKEDFLOAT 1";
  65156. }
  65157. this.updateEffect(defines, null, null, {
  65158. varyingCount: varyingCount,
  65159. depCount: depCount
  65160. });
  65161. };
  65162. /**
  65163. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  65164. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  65165. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  65166. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  65167. * The gaps between physical kernels are compensated for in the weighting of the samples
  65168. * @param idealKernel Ideal blur kernel.
  65169. * @return Nearest best kernel.
  65170. */
  65171. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  65172. var v = Math.round(idealKernel);
  65173. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  65174. var k = _a[_i];
  65175. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  65176. return Math.max(k, 3);
  65177. }
  65178. }
  65179. return Math.max(v, 3);
  65180. };
  65181. /**
  65182. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  65183. * @param x The point on the Gaussian distribution to sample.
  65184. * @return the value of the Gaussian function at x.
  65185. */
  65186. BlurPostProcess.prototype._gaussianWeight = function (x) {
  65187. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  65188. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  65189. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  65190. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  65191. // truncated at around 1.3% of peak strength.
  65192. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  65193. var sigma = (1 / 3);
  65194. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  65195. var exponent = -((x * x) / (2.0 * sigma * sigma));
  65196. var weight = (1.0 / denominator) * Math.exp(exponent);
  65197. return weight;
  65198. };
  65199. /**
  65200. * Generates a string that can be used as a floating point number in GLSL.
  65201. * @param x Value to print.
  65202. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  65203. * @return GLSL float string.
  65204. */
  65205. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  65206. if (decimalFigures === void 0) { decimalFigures = 8; }
  65207. return x.toFixed(decimalFigures).replace(/0+$/, '');
  65208. };
  65209. return BlurPostProcess;
  65210. }(BABYLON.PostProcess));
  65211. BABYLON.BlurPostProcess = BlurPostProcess;
  65212. })(BABYLON || (BABYLON = {}));
  65213. //# sourceMappingURL=babylon.blurPostProcess.js.map
  65214. var BABYLON;
  65215. (function (BABYLON) {
  65216. var Bone = /** @class */ (function (_super) {
  65217. __extends(Bone, _super);
  65218. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  65219. if (parentBone === void 0) { parentBone = null; }
  65220. if (localMatrix === void 0) { localMatrix = null; }
  65221. if (restPose === void 0) { restPose = null; }
  65222. if (baseMatrix === void 0) { baseMatrix = null; }
  65223. if (index === void 0) { index = null; }
  65224. var _this = _super.call(this, name, skeleton.getScene()) || this;
  65225. _this.name = name;
  65226. _this.children = new Array();
  65227. _this.animations = new Array();
  65228. // Set this value to map this bone to a different index in the transform matrices.
  65229. // Set this value to -1 to exclude the bone from the transform matrices.
  65230. _this._index = null;
  65231. _this._worldTransform = new BABYLON.Matrix();
  65232. _this._absoluteTransform = new BABYLON.Matrix();
  65233. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  65234. _this._scaleMatrix = BABYLON.Matrix.Identity();
  65235. _this._scaleVector = BABYLON.Vector3.One();
  65236. _this._negateScaleChildren = BABYLON.Vector3.One();
  65237. _this._scalingDeterminant = 1;
  65238. _this._skeleton = skeleton;
  65239. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  65240. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  65241. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  65242. _this._index = index;
  65243. skeleton.bones.push(_this);
  65244. _this.setParent(parentBone, false);
  65245. _this._updateDifferenceMatrix();
  65246. return _this;
  65247. }
  65248. Object.defineProperty(Bone.prototype, "_matrix", {
  65249. get: function () {
  65250. return this._localMatrix;
  65251. },
  65252. set: function (val) {
  65253. if (this._localMatrix) {
  65254. this._localMatrix.copyFrom(val);
  65255. }
  65256. else {
  65257. this._localMatrix = val;
  65258. }
  65259. },
  65260. enumerable: true,
  65261. configurable: true
  65262. });
  65263. // Members
  65264. Bone.prototype.getSkeleton = function () {
  65265. return this._skeleton;
  65266. };
  65267. Bone.prototype.getParent = function () {
  65268. return this._parent;
  65269. };
  65270. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  65271. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65272. if (this._parent === parent) {
  65273. return;
  65274. }
  65275. if (this._parent) {
  65276. var index = this._parent.children.indexOf(this);
  65277. if (index !== -1) {
  65278. this._parent.children.splice(index, 1);
  65279. }
  65280. }
  65281. this._parent = parent;
  65282. if (this._parent) {
  65283. this._parent.children.push(this);
  65284. }
  65285. if (updateDifferenceMatrix) {
  65286. this._updateDifferenceMatrix();
  65287. }
  65288. };
  65289. Bone.prototype.getLocalMatrix = function () {
  65290. return this._localMatrix;
  65291. };
  65292. Bone.prototype.getBaseMatrix = function () {
  65293. return this._baseMatrix;
  65294. };
  65295. Bone.prototype.getRestPose = function () {
  65296. return this._restPose;
  65297. };
  65298. Bone.prototype.returnToRest = function () {
  65299. this.updateMatrix(this._restPose.clone());
  65300. };
  65301. Bone.prototype.getWorldMatrix = function () {
  65302. return this._worldTransform;
  65303. };
  65304. Bone.prototype.getInvertedAbsoluteTransform = function () {
  65305. return this._invertedAbsoluteTransform;
  65306. };
  65307. Bone.prototype.getAbsoluteTransform = function () {
  65308. return this._absoluteTransform;
  65309. };
  65310. Object.defineProperty(Bone.prototype, "position", {
  65311. // Properties (matches AbstractMesh properties)
  65312. get: function () {
  65313. return this.getPosition();
  65314. },
  65315. set: function (newPosition) {
  65316. this.setPosition(newPosition);
  65317. },
  65318. enumerable: true,
  65319. configurable: true
  65320. });
  65321. Object.defineProperty(Bone.prototype, "rotation", {
  65322. get: function () {
  65323. return this.getRotation();
  65324. },
  65325. set: function (newRotation) {
  65326. this.setRotation(newRotation);
  65327. },
  65328. enumerable: true,
  65329. configurable: true
  65330. });
  65331. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  65332. get: function () {
  65333. return this.getRotationQuaternion();
  65334. },
  65335. set: function (newRotation) {
  65336. this.setRotationQuaternion(newRotation);
  65337. },
  65338. enumerable: true,
  65339. configurable: true
  65340. });
  65341. Object.defineProperty(Bone.prototype, "scaling", {
  65342. get: function () {
  65343. return this.getScale();
  65344. },
  65345. set: function (newScaling) {
  65346. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  65347. },
  65348. enumerable: true,
  65349. configurable: true
  65350. });
  65351. // Methods
  65352. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  65353. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65354. this._baseMatrix = matrix.clone();
  65355. this._localMatrix = matrix.clone();
  65356. this._skeleton._markAsDirty();
  65357. if (updateDifferenceMatrix) {
  65358. this._updateDifferenceMatrix();
  65359. }
  65360. };
  65361. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  65362. if (!rootMatrix) {
  65363. rootMatrix = this._baseMatrix;
  65364. }
  65365. if (this._parent) {
  65366. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65367. }
  65368. else {
  65369. this._absoluteTransform.copyFrom(rootMatrix);
  65370. }
  65371. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  65372. for (var index = 0; index < this.children.length; index++) {
  65373. this.children[index]._updateDifferenceMatrix();
  65374. }
  65375. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  65376. };
  65377. Bone.prototype.markAsDirty = function () {
  65378. this._currentRenderId++;
  65379. this._skeleton._markAsDirty();
  65380. };
  65381. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  65382. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  65383. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  65384. // all animation may be coming from a library skeleton, so may need to create animation
  65385. if (this.animations.length === 0) {
  65386. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  65387. this.animations[0].setKeys([]);
  65388. }
  65389. // get animation info / verify there is such a range from the source bone
  65390. var sourceRange = source.animations[0].getRange(rangeName);
  65391. if (!sourceRange) {
  65392. return false;
  65393. }
  65394. var from = sourceRange.from;
  65395. var to = sourceRange.to;
  65396. var sourceKeys = source.animations[0].getKeys();
  65397. // rescaling prep
  65398. var sourceBoneLength = source.length;
  65399. var sourceParent = source.getParent();
  65400. var parent = this.getParent();
  65401. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  65402. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  65403. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  65404. var destKeys = this.animations[0].getKeys();
  65405. // loop vars declaration
  65406. var orig;
  65407. var origTranslation;
  65408. var mat;
  65409. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  65410. orig = sourceKeys[key];
  65411. if (orig.frame >= from && orig.frame <= to) {
  65412. if (rescaleAsRequired) {
  65413. mat = orig.value.clone();
  65414. // scale based on parent ratio, when bone has parent
  65415. if (parentScalingReqd) {
  65416. origTranslation = mat.getTranslation();
  65417. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  65418. // scale based on skeleton dimension ratio when root bone, and value is passed
  65419. }
  65420. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  65421. origTranslation = mat.getTranslation();
  65422. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  65423. // use original when root bone, and no data for skelDimensionsRatio
  65424. }
  65425. else {
  65426. mat = orig.value;
  65427. }
  65428. }
  65429. else {
  65430. mat = orig.value;
  65431. }
  65432. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65433. }
  65434. }
  65435. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65436. return true;
  65437. };
  65438. /**
  65439. * Translate the bone in local or world space.
  65440. * @param vec The amount to translate the bone.
  65441. * @param space The space that the translation is in.
  65442. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65443. */
  65444. Bone.prototype.translate = function (vec, space, mesh) {
  65445. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65446. var lm = this.getLocalMatrix();
  65447. if (space == BABYLON.Space.LOCAL) {
  65448. lm.m[12] += vec.x;
  65449. lm.m[13] += vec.y;
  65450. lm.m[14] += vec.z;
  65451. }
  65452. else {
  65453. var wm = null;
  65454. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65455. if (mesh) {
  65456. wm = mesh.getWorldMatrix();
  65457. }
  65458. this._skeleton.computeAbsoluteTransforms();
  65459. var tmat = Bone._tmpMats[0];
  65460. var tvec = Bone._tmpVecs[0];
  65461. if (this._parent) {
  65462. if (mesh && wm) {
  65463. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65464. tmat.multiplyToRef(wm, tmat);
  65465. }
  65466. else {
  65467. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65468. }
  65469. }
  65470. tmat.m[12] = 0;
  65471. tmat.m[13] = 0;
  65472. tmat.m[14] = 0;
  65473. tmat.invert();
  65474. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65475. lm.m[12] += tvec.x;
  65476. lm.m[13] += tvec.y;
  65477. lm.m[14] += tvec.z;
  65478. }
  65479. this.markAsDirty();
  65480. };
  65481. /**
  65482. * Set the postion of the bone in local or world space.
  65483. * @param position The position to set the bone.
  65484. * @param space The space that the position is in.
  65485. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65486. */
  65487. Bone.prototype.setPosition = function (position, space, mesh) {
  65488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65489. var lm = this.getLocalMatrix();
  65490. if (space == BABYLON.Space.LOCAL) {
  65491. lm.m[12] = position.x;
  65492. lm.m[13] = position.y;
  65493. lm.m[14] = position.z;
  65494. }
  65495. else {
  65496. var wm = null;
  65497. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65498. if (mesh) {
  65499. wm = mesh.getWorldMatrix();
  65500. }
  65501. this._skeleton.computeAbsoluteTransforms();
  65502. var tmat = Bone._tmpMats[0];
  65503. var vec = Bone._tmpVecs[0];
  65504. if (this._parent) {
  65505. if (mesh && wm) {
  65506. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65507. tmat.multiplyToRef(wm, tmat);
  65508. }
  65509. else {
  65510. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65511. }
  65512. }
  65513. tmat.invert();
  65514. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65515. lm.m[12] = vec.x;
  65516. lm.m[13] = vec.y;
  65517. lm.m[14] = vec.z;
  65518. }
  65519. this.markAsDirty();
  65520. };
  65521. /**
  65522. * Set the absolute postion of the bone (world space).
  65523. * @param position The position to set the bone.
  65524. * @param mesh The mesh that this bone is attached to.
  65525. */
  65526. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65527. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65528. };
  65529. /**
  65530. * Set the scale of the bone on the x, y and z axes.
  65531. * @param x The scale of the bone on the x axis.
  65532. * @param x The scale of the bone on the y axis.
  65533. * @param z The scale of the bone on the z axis.
  65534. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65535. */
  65536. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65537. if (scaleChildren === void 0) { scaleChildren = false; }
  65538. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65539. if (!scaleChildren) {
  65540. this._negateScaleChildren.x = 1 / x;
  65541. this._negateScaleChildren.y = 1 / y;
  65542. this._negateScaleChildren.z = 1 / z;
  65543. }
  65544. this._syncScaleVector();
  65545. }
  65546. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65547. };
  65548. /**
  65549. * Scale the bone on the x, y and z axes.
  65550. * @param x The amount to scale the bone on the x axis.
  65551. * @param x The amount to scale the bone on the y axis.
  65552. * @param z The amount to scale the bone on the z axis.
  65553. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65554. */
  65555. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65556. if (scaleChildren === void 0) { scaleChildren = false; }
  65557. var locMat = this.getLocalMatrix();
  65558. var origLocMat = Bone._tmpMats[0];
  65559. origLocMat.copyFrom(locMat);
  65560. var origLocMatInv = Bone._tmpMats[1];
  65561. origLocMatInv.copyFrom(origLocMat);
  65562. origLocMatInv.invert();
  65563. var scaleMat = Bone._tmpMats[2];
  65564. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65565. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65566. this._scaleVector.x *= x;
  65567. this._scaleVector.y *= y;
  65568. this._scaleVector.z *= z;
  65569. locMat.multiplyToRef(origLocMatInv, locMat);
  65570. locMat.multiplyToRef(scaleMat, locMat);
  65571. locMat.multiplyToRef(origLocMat, locMat);
  65572. var parent = this.getParent();
  65573. if (parent) {
  65574. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65575. }
  65576. else {
  65577. this.getAbsoluteTransform().copyFrom(locMat);
  65578. }
  65579. var len = this.children.length;
  65580. scaleMat.invert();
  65581. for (var i = 0; i < len; i++) {
  65582. var child = this.children[i];
  65583. var cm = child.getLocalMatrix();
  65584. cm.multiplyToRef(scaleMat, cm);
  65585. var lm = child.getLocalMatrix();
  65586. lm.m[12] *= x;
  65587. lm.m[13] *= y;
  65588. lm.m[14] *= z;
  65589. }
  65590. this.computeAbsoluteTransforms();
  65591. if (scaleChildren) {
  65592. for (var i = 0; i < len; i++) {
  65593. this.children[i].scale(x, y, z, scaleChildren);
  65594. }
  65595. }
  65596. this.markAsDirty();
  65597. };
  65598. /**
  65599. * Set the yaw, pitch, and roll of the bone in local or world space.
  65600. * @param yaw The rotation of the bone on the y axis.
  65601. * @param pitch The rotation of the bone on the x axis.
  65602. * @param roll The rotation of the bone on the z axis.
  65603. * @param space The space that the axes of rotation are in.
  65604. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65605. */
  65606. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65608. var rotMat = Bone._tmpMats[0];
  65609. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65610. var rotMatInv = Bone._tmpMats[1];
  65611. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65612. rotMatInv.multiplyToRef(rotMat, rotMat);
  65613. this._rotateWithMatrix(rotMat, space, mesh);
  65614. };
  65615. /**
  65616. * Rotate the bone on an axis in local or world space.
  65617. * @param axis The axis to rotate the bone on.
  65618. * @param amount The amount to rotate the bone.
  65619. * @param space The space that the axis is in.
  65620. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65621. */
  65622. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65623. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65624. var rmat = Bone._tmpMats[0];
  65625. rmat.m[12] = 0;
  65626. rmat.m[13] = 0;
  65627. rmat.m[14] = 0;
  65628. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65629. this._rotateWithMatrix(rmat, space, mesh);
  65630. };
  65631. /**
  65632. * Set the rotation of the bone to a particular axis angle in local or world space.
  65633. * @param axis The axis to rotate the bone on.
  65634. * @param angle The angle that the bone should be rotated to.
  65635. * @param space The space that the axis is in.
  65636. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65637. */
  65638. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65640. var rotMat = Bone._tmpMats[0];
  65641. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65642. var rotMatInv = Bone._tmpMats[1];
  65643. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65644. rotMatInv.multiplyToRef(rotMat, rotMat);
  65645. this._rotateWithMatrix(rotMat, space, mesh);
  65646. };
  65647. /**
  65648. * Set the euler rotation of the bone in local of world space.
  65649. * @param rotation The euler rotation that the bone should be set to.
  65650. * @param space The space that the rotation is in.
  65651. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65652. */
  65653. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65655. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65656. };
  65657. /**
  65658. * Set the quaternion rotation of the bone in local of world space.
  65659. * @param quat The quaternion rotation that the bone should be set to.
  65660. * @param space The space that the rotation is in.
  65661. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65662. */
  65663. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65664. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65665. var rotMatInv = Bone._tmpMats[0];
  65666. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65667. var rotMat = Bone._tmpMats[1];
  65668. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  65669. rotMatInv.multiplyToRef(rotMat, rotMat);
  65670. this._rotateWithMatrix(rotMat, space, mesh);
  65671. };
  65672. /**
  65673. * Set the rotation matrix of the bone in local of world space.
  65674. * @param rotMat The rotation matrix that the bone should be set to.
  65675. * @param space The space that the rotation is in.
  65676. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65677. */
  65678. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  65679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65680. var rotMatInv = Bone._tmpMats[0];
  65681. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65682. var rotMat2 = Bone._tmpMats[1];
  65683. rotMat2.copyFrom(rotMat);
  65684. rotMatInv.multiplyToRef(rotMat, rotMat2);
  65685. this._rotateWithMatrix(rotMat2, space, mesh);
  65686. };
  65687. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  65688. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65689. var lmat = this.getLocalMatrix();
  65690. var lx = lmat.m[12];
  65691. var ly = lmat.m[13];
  65692. var lz = lmat.m[14];
  65693. var parent = this.getParent();
  65694. var parentScale = Bone._tmpMats[3];
  65695. var parentScaleInv = Bone._tmpMats[4];
  65696. if (parent) {
  65697. if (space == BABYLON.Space.WORLD) {
  65698. if (mesh) {
  65699. parentScale.copyFrom(mesh.getWorldMatrix());
  65700. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  65701. }
  65702. else {
  65703. parentScale.copyFrom(parent.getAbsoluteTransform());
  65704. }
  65705. }
  65706. else {
  65707. parentScale = parent._scaleMatrix;
  65708. }
  65709. parentScaleInv.copyFrom(parentScale);
  65710. parentScaleInv.invert();
  65711. lmat.multiplyToRef(parentScale, lmat);
  65712. lmat.multiplyToRef(rmat, lmat);
  65713. lmat.multiplyToRef(parentScaleInv, lmat);
  65714. }
  65715. else {
  65716. if (space == BABYLON.Space.WORLD && mesh) {
  65717. parentScale.copyFrom(mesh.getWorldMatrix());
  65718. parentScaleInv.copyFrom(parentScale);
  65719. parentScaleInv.invert();
  65720. lmat.multiplyToRef(parentScale, lmat);
  65721. lmat.multiplyToRef(rmat, lmat);
  65722. lmat.multiplyToRef(parentScaleInv, lmat);
  65723. }
  65724. else {
  65725. lmat.multiplyToRef(rmat, lmat);
  65726. }
  65727. }
  65728. lmat.m[12] = lx;
  65729. lmat.m[13] = ly;
  65730. lmat.m[14] = lz;
  65731. this.computeAbsoluteTransforms();
  65732. this.markAsDirty();
  65733. };
  65734. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  65735. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65736. if (space == BABYLON.Space.WORLD) {
  65737. var scaleMatrix = Bone._tmpMats[2];
  65738. scaleMatrix.copyFrom(this._scaleMatrix);
  65739. rotMatInv.copyFrom(this.getAbsoluteTransform());
  65740. if (mesh) {
  65741. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  65742. var meshScale = Bone._tmpMats[3];
  65743. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  65744. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  65745. }
  65746. rotMatInv.invert();
  65747. scaleMatrix.m[0] *= this._scalingDeterminant;
  65748. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65749. }
  65750. else {
  65751. rotMatInv.copyFrom(this.getLocalMatrix());
  65752. rotMatInv.invert();
  65753. var scaleMatrix = Bone._tmpMats[2];
  65754. scaleMatrix.copyFrom(this._scaleMatrix);
  65755. if (this._parent) {
  65756. var pscaleMatrix = Bone._tmpMats[3];
  65757. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  65758. pscaleMatrix.invert();
  65759. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  65760. }
  65761. else {
  65762. scaleMatrix.m[0] *= this._scalingDeterminant;
  65763. }
  65764. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65765. }
  65766. };
  65767. /**
  65768. * Get the scale of the bone
  65769. * @returns the scale of the bone
  65770. */
  65771. Bone.prototype.getScale = function () {
  65772. return this._scaleVector.clone();
  65773. };
  65774. /**
  65775. * Copy the scale of the bone to a vector3.
  65776. * @param result The vector3 to copy the scale to
  65777. */
  65778. Bone.prototype.getScaleToRef = function (result) {
  65779. result.copyFrom(this._scaleVector);
  65780. };
  65781. /**
  65782. * Get the position of the bone in local or world space.
  65783. * @param space The space that the returned position is in.
  65784. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65785. * @returns The position of the bone
  65786. */
  65787. Bone.prototype.getPosition = function (space, mesh) {
  65788. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65789. if (mesh === void 0) { mesh = null; }
  65790. var pos = BABYLON.Vector3.Zero();
  65791. this.getPositionToRef(space, mesh, pos);
  65792. return pos;
  65793. };
  65794. /**
  65795. * Copy the position of the bone to a vector3 in local or world space.
  65796. * @param space The space that the returned position is in.
  65797. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65798. * @param result The vector3 to copy the position to.
  65799. */
  65800. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  65801. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65802. if (space == BABYLON.Space.LOCAL) {
  65803. var lm = this.getLocalMatrix();
  65804. result.x = lm.m[12];
  65805. result.y = lm.m[13];
  65806. result.z = lm.m[14];
  65807. }
  65808. else {
  65809. var wm = null;
  65810. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65811. if (mesh) {
  65812. wm = mesh.getWorldMatrix();
  65813. }
  65814. this._skeleton.computeAbsoluteTransforms();
  65815. var tmat = Bone._tmpMats[0];
  65816. if (mesh && wm) {
  65817. tmat.copyFrom(this.getAbsoluteTransform());
  65818. tmat.multiplyToRef(wm, tmat);
  65819. }
  65820. else {
  65821. tmat = this.getAbsoluteTransform();
  65822. }
  65823. result.x = tmat.m[12];
  65824. result.y = tmat.m[13];
  65825. result.z = tmat.m[14];
  65826. }
  65827. };
  65828. /**
  65829. * Get the absolute position of the bone (world space).
  65830. * @param mesh The mesh that this bone is attached to.
  65831. * @returns The absolute position of the bone
  65832. */
  65833. Bone.prototype.getAbsolutePosition = function (mesh) {
  65834. if (mesh === void 0) { mesh = null; }
  65835. var pos = BABYLON.Vector3.Zero();
  65836. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  65837. return pos;
  65838. };
  65839. /**
  65840. * Copy the absolute position of the bone (world space) to the result param.
  65841. * @param mesh The mesh that this bone is attached to.
  65842. * @param result The vector3 to copy the absolute position to.
  65843. */
  65844. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  65845. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  65846. };
  65847. /**
  65848. * Compute the absolute transforms of this bone and its children.
  65849. */
  65850. Bone.prototype.computeAbsoluteTransforms = function () {
  65851. if (this._parent) {
  65852. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65853. }
  65854. else {
  65855. this._absoluteTransform.copyFrom(this._localMatrix);
  65856. var poseMatrix = this._skeleton.getPoseMatrix();
  65857. if (poseMatrix) {
  65858. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  65859. }
  65860. }
  65861. var children = this.children;
  65862. var len = children.length;
  65863. for (var i = 0; i < len; i++) {
  65864. children[i].computeAbsoluteTransforms();
  65865. }
  65866. };
  65867. Bone.prototype._syncScaleVector = function () {
  65868. var lm = this.getLocalMatrix();
  65869. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  65870. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  65871. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  65872. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  65873. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  65874. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  65875. this._scaleVector.x = xs * Math.sqrt(xsq);
  65876. this._scaleVector.y = ys * Math.sqrt(ysq);
  65877. this._scaleVector.z = zs * Math.sqrt(zsq);
  65878. if (this._parent) {
  65879. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  65880. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  65881. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  65882. }
  65883. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  65884. };
  65885. /**
  65886. * Get the world direction from an axis that is in the local space of the bone.
  65887. * @param localAxis The local direction that is used to compute the world direction.
  65888. * @param mesh The mesh that this bone is attached to.
  65889. * @returns The world direction
  65890. */
  65891. Bone.prototype.getDirection = function (localAxis, mesh) {
  65892. if (mesh === void 0) { mesh = null; }
  65893. var result = BABYLON.Vector3.Zero();
  65894. this.getDirectionToRef(localAxis, mesh, result);
  65895. return result;
  65896. };
  65897. /**
  65898. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  65899. * @param localAxis The local direction that is used to compute the world direction.
  65900. * @param mesh The mesh that this bone is attached to.
  65901. * @param result The vector3 that the world direction will be copied to.
  65902. */
  65903. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  65904. if (mesh === void 0) { mesh = null; }
  65905. var wm = null;
  65906. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65907. if (mesh) {
  65908. wm = mesh.getWorldMatrix();
  65909. }
  65910. this._skeleton.computeAbsoluteTransforms();
  65911. var mat = Bone._tmpMats[0];
  65912. mat.copyFrom(this.getAbsoluteTransform());
  65913. if (mesh && wm) {
  65914. mat.multiplyToRef(wm, mat);
  65915. }
  65916. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  65917. result.normalize();
  65918. };
  65919. /**
  65920. * Get the euler rotation of the bone in local or world space.
  65921. * @param space The space that the rotation should be in.
  65922. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65923. * @returns The euler rotation
  65924. */
  65925. Bone.prototype.getRotation = function (space, mesh) {
  65926. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65927. if (mesh === void 0) { mesh = null; }
  65928. var result = BABYLON.Vector3.Zero();
  65929. this.getRotationToRef(space, mesh, result);
  65930. return result;
  65931. };
  65932. /**
  65933. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  65934. * @param space The space that the rotation should be in.
  65935. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65936. * @param result The vector3 that the rotation should be copied to.
  65937. */
  65938. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  65939. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65940. if (mesh === void 0) { mesh = null; }
  65941. var quat = Bone._tmpQuat;
  65942. this.getRotationQuaternionToRef(space, mesh, quat);
  65943. quat.toEulerAnglesToRef(result);
  65944. };
  65945. /**
  65946. * Get the quaternion rotation of the bone in either local or world space.
  65947. * @param space The space that the rotation should be in.
  65948. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65949. * @returns The quaternion rotation
  65950. */
  65951. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  65952. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65953. if (mesh === void 0) { mesh = null; }
  65954. var result = BABYLON.Quaternion.Identity();
  65955. this.getRotationQuaternionToRef(space, mesh, result);
  65956. return result;
  65957. };
  65958. /**
  65959. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  65960. * @param space The space that the rotation should be in.
  65961. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65962. * @param result The quaternion that the rotation should be copied to.
  65963. */
  65964. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  65965. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65966. if (mesh === void 0) { mesh = null; }
  65967. if (space == BABYLON.Space.LOCAL) {
  65968. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65969. }
  65970. else {
  65971. var mat = Bone._tmpMats[0];
  65972. var amat = this.getAbsoluteTransform();
  65973. if (mesh) {
  65974. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  65975. }
  65976. else {
  65977. mat.copyFrom(amat);
  65978. }
  65979. mat.m[0] *= this._scalingDeterminant;
  65980. mat.m[1] *= this._scalingDeterminant;
  65981. mat.m[2] *= this._scalingDeterminant;
  65982. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  65983. }
  65984. };
  65985. /**
  65986. * Get the rotation matrix of the bone in local or world space.
  65987. * @param space The space that the rotation should be in.
  65988. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65989. * @returns The rotation matrix
  65990. */
  65991. Bone.prototype.getRotationMatrix = function (space, mesh) {
  65992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65993. var result = BABYLON.Matrix.Identity();
  65994. this.getRotationMatrixToRef(space, mesh, result);
  65995. return result;
  65996. };
  65997. /**
  65998. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  65999. * @param space The space that the rotation should be in.
  66000. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66001. * @param result The quaternion that the rotation should be copied to.
  66002. */
  66003. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  66004. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66005. if (space == BABYLON.Space.LOCAL) {
  66006. this.getLocalMatrix().getRotationMatrixToRef(result);
  66007. }
  66008. else {
  66009. var mat = Bone._tmpMats[0];
  66010. var amat = this.getAbsoluteTransform();
  66011. if (mesh) {
  66012. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66013. }
  66014. else {
  66015. mat.copyFrom(amat);
  66016. }
  66017. mat.m[0] *= this._scalingDeterminant;
  66018. mat.m[1] *= this._scalingDeterminant;
  66019. mat.m[2] *= this._scalingDeterminant;
  66020. mat.getRotationMatrixToRef(result);
  66021. }
  66022. };
  66023. /**
  66024. * Get the world position of a point that is in the local space of the bone.
  66025. * @param position The local position
  66026. * @param mesh The mesh that this bone is attached to.
  66027. * @returns The world position
  66028. */
  66029. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  66030. if (mesh === void 0) { mesh = null; }
  66031. var result = BABYLON.Vector3.Zero();
  66032. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  66033. return result;
  66034. };
  66035. /**
  66036. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  66037. * @param position The local position
  66038. * @param mesh The mesh that this bone is attached to.
  66039. * @param result The vector3 that the world position should be copied to.
  66040. */
  66041. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  66042. if (mesh === void 0) { mesh = null; }
  66043. var wm = null;
  66044. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66045. if (mesh) {
  66046. wm = mesh.getWorldMatrix();
  66047. }
  66048. this._skeleton.computeAbsoluteTransforms();
  66049. var tmat = Bone._tmpMats[0];
  66050. if (mesh && wm) {
  66051. tmat.copyFrom(this.getAbsoluteTransform());
  66052. tmat.multiplyToRef(wm, tmat);
  66053. }
  66054. else {
  66055. tmat = this.getAbsoluteTransform();
  66056. }
  66057. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66058. };
  66059. /**
  66060. * Get the local position of a point that is in world space.
  66061. * @param position The world position
  66062. * @param mesh The mesh that this bone is attached to.
  66063. * @returns The local position
  66064. */
  66065. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  66066. if (mesh === void 0) { mesh = null; }
  66067. var result = BABYLON.Vector3.Zero();
  66068. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  66069. return result;
  66070. };
  66071. /**
  66072. * Get the local position of a point that is in world space and copy it to the result param.
  66073. * @param position The world position
  66074. * @param mesh The mesh that this bone is attached to.
  66075. * @param result The vector3 that the local position should be copied to.
  66076. */
  66077. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  66078. if (mesh === void 0) { mesh = null; }
  66079. var wm = null;
  66080. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66081. if (mesh) {
  66082. wm = mesh.getWorldMatrix();
  66083. }
  66084. this._skeleton.computeAbsoluteTransforms();
  66085. var tmat = Bone._tmpMats[0];
  66086. tmat.copyFrom(this.getAbsoluteTransform());
  66087. if (mesh && wm) {
  66088. tmat.multiplyToRef(wm, tmat);
  66089. }
  66090. tmat.invert();
  66091. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66092. };
  66093. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66094. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  66095. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66096. return Bone;
  66097. }(BABYLON.Node));
  66098. BABYLON.Bone = Bone;
  66099. })(BABYLON || (BABYLON = {}));
  66100. //# sourceMappingURL=babylon.bone.js.map
  66101. var BABYLON;
  66102. (function (BABYLON) {
  66103. var BoneIKController = /** @class */ (function () {
  66104. function BoneIKController(mesh, bone, options) {
  66105. this.targetPosition = BABYLON.Vector3.Zero();
  66106. this.poleTargetPosition = BABYLON.Vector3.Zero();
  66107. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  66108. this.poleAngle = 0;
  66109. this.slerpAmount = 1;
  66110. this._bone1Quat = BABYLON.Quaternion.Identity();
  66111. this._bone1Mat = BABYLON.Matrix.Identity();
  66112. this._bone2Ang = Math.PI;
  66113. this._maxAngle = Math.PI;
  66114. this._rightHandedSystem = false;
  66115. this._bendAxis = BABYLON.Vector3.Right();
  66116. this._slerping = false;
  66117. this._adjustRoll = 0;
  66118. this._bone2 = bone;
  66119. this._bone1 = bone.getParent();
  66120. if (!this._bone1) {
  66121. return;
  66122. }
  66123. this.mesh = mesh;
  66124. var bonePos = bone.getPosition();
  66125. if (bone.getAbsoluteTransform().determinant() > 0) {
  66126. this._rightHandedSystem = true;
  66127. this._bendAxis.x = 0;
  66128. this._bendAxis.y = 0;
  66129. this._bendAxis.z = -1;
  66130. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  66131. this._adjustRoll = Math.PI * .5;
  66132. this._bendAxis.z = 1;
  66133. }
  66134. }
  66135. if (this._bone1.length) {
  66136. var boneScale1 = this._bone1.getScale();
  66137. var boneScale2 = this._bone2.getScale();
  66138. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  66139. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  66140. }
  66141. else if (this._bone1.children[0]) {
  66142. mesh.computeWorldMatrix(true);
  66143. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  66144. var pos2 = this._bone2.getAbsolutePosition(mesh);
  66145. var pos3 = this._bone1.getAbsolutePosition(mesh);
  66146. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  66147. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  66148. }
  66149. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  66150. this.maxAngle = Math.PI;
  66151. if (options) {
  66152. if (options.targetMesh) {
  66153. this.targetMesh = options.targetMesh;
  66154. this.targetMesh.computeWorldMatrix(true);
  66155. }
  66156. if (options.poleTargetMesh) {
  66157. this.poleTargetMesh = options.poleTargetMesh;
  66158. this.poleTargetMesh.computeWorldMatrix(true);
  66159. }
  66160. else if (options.poleTargetBone) {
  66161. this.poleTargetBone = options.poleTargetBone;
  66162. }
  66163. else if (this._bone1.getParent()) {
  66164. this.poleTargetBone = this._bone1.getParent();
  66165. }
  66166. if (options.poleTargetLocalOffset) {
  66167. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  66168. }
  66169. if (options.poleAngle) {
  66170. this.poleAngle = options.poleAngle;
  66171. }
  66172. if (options.bendAxis) {
  66173. this._bendAxis.copyFrom(options.bendAxis);
  66174. }
  66175. if (options.maxAngle) {
  66176. this.maxAngle = options.maxAngle;
  66177. }
  66178. if (options.slerpAmount) {
  66179. this.slerpAmount = options.slerpAmount;
  66180. }
  66181. }
  66182. }
  66183. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  66184. get: function () {
  66185. return this._maxAngle;
  66186. },
  66187. set: function (value) {
  66188. this._setMaxAngle(value);
  66189. },
  66190. enumerable: true,
  66191. configurable: true
  66192. });
  66193. BoneIKController.prototype._setMaxAngle = function (ang) {
  66194. if (ang < 0) {
  66195. ang = 0;
  66196. }
  66197. if (ang > Math.PI || ang == undefined) {
  66198. ang = Math.PI;
  66199. }
  66200. this._maxAngle = ang;
  66201. var a = this._bone1Length;
  66202. var b = this._bone2Length;
  66203. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  66204. };
  66205. BoneIKController.prototype.update = function () {
  66206. var bone1 = this._bone1;
  66207. if (!bone1) {
  66208. return;
  66209. }
  66210. var target = this.targetPosition;
  66211. var poleTarget = this.poleTargetPosition;
  66212. var mat1 = BoneIKController._tmpMats[0];
  66213. var mat2 = BoneIKController._tmpMats[1];
  66214. if (this.targetMesh) {
  66215. target.copyFrom(this.targetMesh.getAbsolutePosition());
  66216. }
  66217. if (this.poleTargetBone) {
  66218. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  66219. }
  66220. else if (this.poleTargetMesh) {
  66221. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  66222. }
  66223. var bonePos = BoneIKController._tmpVecs[0];
  66224. var zaxis = BoneIKController._tmpVecs[1];
  66225. var xaxis = BoneIKController._tmpVecs[2];
  66226. var yaxis = BoneIKController._tmpVecs[3];
  66227. var upAxis = BoneIKController._tmpVecs[4];
  66228. var _tmpQuat = BoneIKController._tmpQuat;
  66229. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  66230. poleTarget.subtractToRef(bonePos, upAxis);
  66231. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  66232. upAxis.y = 1;
  66233. }
  66234. else {
  66235. upAxis.normalize();
  66236. }
  66237. target.subtractToRef(bonePos, yaxis);
  66238. yaxis.normalize();
  66239. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  66240. zaxis.normalize();
  66241. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  66242. xaxis.normalize();
  66243. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  66244. var a = this._bone1Length;
  66245. var b = this._bone2Length;
  66246. var c = BABYLON.Vector3.Distance(bonePos, target);
  66247. if (this._maxReach > 0) {
  66248. c = Math.min(this._maxReach, c);
  66249. }
  66250. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  66251. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  66252. if (acosa > 1) {
  66253. acosa = 1;
  66254. }
  66255. if (acosb > 1) {
  66256. acosb = 1;
  66257. }
  66258. if (acosa < -1) {
  66259. acosa = -1;
  66260. }
  66261. if (acosb < -1) {
  66262. acosb = -1;
  66263. }
  66264. var angA = Math.acos(acosa);
  66265. var angB = Math.acos(acosb);
  66266. var angC = -angA - angB;
  66267. if (this._rightHandedSystem) {
  66268. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  66269. mat2.multiplyToRef(mat1, mat1);
  66270. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  66271. mat2.multiplyToRef(mat1, mat1);
  66272. }
  66273. else {
  66274. var _tmpVec = BoneIKController._tmpVecs[5];
  66275. _tmpVec.copyFrom(this._bendAxis);
  66276. _tmpVec.x *= -1;
  66277. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  66278. mat2.multiplyToRef(mat1, mat1);
  66279. }
  66280. if (this.poleAngle) {
  66281. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  66282. mat1.multiplyToRef(mat2, mat1);
  66283. }
  66284. if (this._bone1) {
  66285. if (this.slerpAmount < 1) {
  66286. if (!this._slerping) {
  66287. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  66288. }
  66289. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  66290. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  66291. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  66292. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  66293. this._slerping = true;
  66294. }
  66295. else {
  66296. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  66297. this._bone1Mat.copyFrom(mat1);
  66298. this._slerping = false;
  66299. }
  66300. }
  66301. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  66302. this._bone2Ang = angC;
  66303. };
  66304. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66305. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  66306. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66307. return BoneIKController;
  66308. }());
  66309. BABYLON.BoneIKController = BoneIKController;
  66310. })(BABYLON || (BABYLON = {}));
  66311. //# sourceMappingURL=babylon.boneIKController.js.map
  66312. var BABYLON;
  66313. (function (BABYLON) {
  66314. var BoneLookController = /** @class */ (function () {
  66315. /**
  66316. * Create a BoneLookController
  66317. * @param mesh the mesh that the bone belongs to
  66318. * @param bone the bone that will be looking to the target
  66319. * @param target the target Vector3 to look at
  66320. * @param settings optional settings:
  66321. * - maxYaw: the maximum angle the bone will yaw to
  66322. * - minYaw: the minimum angle the bone will yaw to
  66323. * - maxPitch: the maximum angle the bone will pitch to
  66324. * - minPitch: the minimum angle the bone will yaw to
  66325. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  66326. * - upAxis: the up axis of the coordinate system
  66327. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66328. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  66329. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  66330. * - adjustYaw: used to make an adjustment to the yaw of the bone
  66331. * - adjustPitch: used to make an adjustment to the pitch of the bone
  66332. * - adjustRoll: used to make an adjustment to the roll of the bone
  66333. **/
  66334. function BoneLookController(mesh, bone, target, options) {
  66335. /**
  66336. * The up axis of the coordinate system that is used when the bone is rotated.
  66337. */
  66338. this.upAxis = BABYLON.Vector3.Up();
  66339. /**
  66340. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66341. */
  66342. this.upAxisSpace = BABYLON.Space.LOCAL;
  66343. /**
  66344. * Used to make an adjustment to the yaw of the bone.
  66345. */
  66346. this.adjustYaw = 0;
  66347. /**
  66348. * Used to make an adjustment to the pitch of the bone.
  66349. */
  66350. this.adjustPitch = 0;
  66351. /**
  66352. * Used to make an adjustment to the roll of the bone.
  66353. */
  66354. this.adjustRoll = 0;
  66355. /**
  66356. * 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).
  66357. */
  66358. this.slerpAmount = 1;
  66359. this._boneQuat = BABYLON.Quaternion.Identity();
  66360. this._slerping = false;
  66361. this._firstFrameSkipped = false;
  66362. this._fowardAxis = BABYLON.Vector3.Forward();
  66363. this.mesh = mesh;
  66364. this.bone = bone;
  66365. this.target = target;
  66366. if (options) {
  66367. if (options.adjustYaw) {
  66368. this.adjustYaw = options.adjustYaw;
  66369. }
  66370. if (options.adjustPitch) {
  66371. this.adjustPitch = options.adjustPitch;
  66372. }
  66373. if (options.adjustRoll) {
  66374. this.adjustRoll = options.adjustRoll;
  66375. }
  66376. if (options.maxYaw != null) {
  66377. this.maxYaw = options.maxYaw;
  66378. }
  66379. else {
  66380. this.maxYaw = Math.PI;
  66381. }
  66382. if (options.minYaw != null) {
  66383. this.minYaw = options.minYaw;
  66384. }
  66385. else {
  66386. this.minYaw = -Math.PI;
  66387. }
  66388. if (options.maxPitch != null) {
  66389. this.maxPitch = options.maxPitch;
  66390. }
  66391. else {
  66392. this.maxPitch = Math.PI;
  66393. }
  66394. if (options.minPitch != null) {
  66395. this.minPitch = options.minPitch;
  66396. }
  66397. else {
  66398. this.minPitch = -Math.PI;
  66399. }
  66400. if (options.slerpAmount != null) {
  66401. this.slerpAmount = options.slerpAmount;
  66402. }
  66403. if (options.upAxis != null) {
  66404. this.upAxis = options.upAxis;
  66405. }
  66406. if (options.upAxisSpace != null) {
  66407. this.upAxisSpace = options.upAxisSpace;
  66408. }
  66409. if (options.yawAxis != null || options.pitchAxis != null) {
  66410. var newYawAxis = BABYLON.Axis.Y;
  66411. var newPitchAxis = BABYLON.Axis.X;
  66412. if (options.yawAxis != null) {
  66413. newYawAxis = options.yawAxis.clone();
  66414. newYawAxis.normalize();
  66415. }
  66416. if (options.pitchAxis != null) {
  66417. newPitchAxis = options.pitchAxis.clone();
  66418. newPitchAxis.normalize();
  66419. }
  66420. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  66421. this._transformYawPitch = BABYLON.Matrix.Identity();
  66422. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  66423. this._transformYawPitchInv = this._transformYawPitch.clone();
  66424. this._transformYawPitch.invert();
  66425. }
  66426. }
  66427. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  66428. this.upAxisSpace = BABYLON.Space.LOCAL;
  66429. }
  66430. }
  66431. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  66432. /**
  66433. * Get/set the minimum yaw angle that the bone can look to.
  66434. */
  66435. get: function () {
  66436. return this._minYaw;
  66437. },
  66438. set: function (value) {
  66439. this._minYaw = value;
  66440. this._minYawSin = Math.sin(value);
  66441. this._minYawCos = Math.cos(value);
  66442. if (this._maxYaw != null) {
  66443. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66444. this._yawRange = this._maxYaw - this._minYaw;
  66445. }
  66446. },
  66447. enumerable: true,
  66448. configurable: true
  66449. });
  66450. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66451. /**
  66452. * Get/set the maximum yaw angle that the bone can look to.
  66453. */
  66454. get: function () {
  66455. return this._maxYaw;
  66456. },
  66457. set: function (value) {
  66458. this._maxYaw = value;
  66459. this._maxYawSin = Math.sin(value);
  66460. this._maxYawCos = Math.cos(value);
  66461. if (this._minYaw != null) {
  66462. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66463. this._yawRange = this._maxYaw - this._minYaw;
  66464. }
  66465. },
  66466. enumerable: true,
  66467. configurable: true
  66468. });
  66469. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66470. /**
  66471. * Get/set the minimum pitch angle that the bone can look to.
  66472. */
  66473. get: function () {
  66474. return this._minPitch;
  66475. },
  66476. set: function (value) {
  66477. this._minPitch = value;
  66478. this._minPitchTan = Math.tan(value);
  66479. },
  66480. enumerable: true,
  66481. configurable: true
  66482. });
  66483. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66484. /**
  66485. * Get/set the maximum pitch angle that the bone can look to.
  66486. */
  66487. get: function () {
  66488. return this._maxPitch;
  66489. },
  66490. set: function (value) {
  66491. this._maxPitch = value;
  66492. this._maxPitchTan = Math.tan(value);
  66493. },
  66494. enumerable: true,
  66495. configurable: true
  66496. });
  66497. /**
  66498. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66499. */
  66500. BoneLookController.prototype.update = function () {
  66501. //skip the first frame when slerping so that the mesh rotation is correct
  66502. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66503. this._firstFrameSkipped = true;
  66504. return;
  66505. }
  66506. var bone = this.bone;
  66507. var bonePos = BoneLookController._tmpVecs[0];
  66508. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66509. var target = this.target;
  66510. var _tmpMat1 = BoneLookController._tmpMats[0];
  66511. var _tmpMat2 = BoneLookController._tmpMats[1];
  66512. var mesh = this.mesh;
  66513. var parentBone = bone.getParent();
  66514. var upAxis = BoneLookController._tmpVecs[1];
  66515. upAxis.copyFrom(this.upAxis);
  66516. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66517. if (this._transformYawPitch) {
  66518. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66519. }
  66520. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66521. }
  66522. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66523. mesh.getDirectionToRef(upAxis, upAxis);
  66524. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66525. upAxis.normalize();
  66526. }
  66527. }
  66528. var checkYaw = false;
  66529. var checkPitch = false;
  66530. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66531. checkYaw = true;
  66532. }
  66533. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66534. checkPitch = true;
  66535. }
  66536. if (checkYaw || checkPitch) {
  66537. var spaceMat = BoneLookController._tmpMats[2];
  66538. var spaceMatInv = BoneLookController._tmpMats[3];
  66539. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66540. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66541. }
  66542. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66543. spaceMat.copyFrom(mesh.getWorldMatrix());
  66544. }
  66545. else {
  66546. var forwardAxis = BoneLookController._tmpVecs[2];
  66547. forwardAxis.copyFrom(this._fowardAxis);
  66548. if (this._transformYawPitch) {
  66549. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66550. }
  66551. if (parentBone) {
  66552. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66553. }
  66554. else {
  66555. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66556. }
  66557. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66558. rightAxis.normalize();
  66559. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66560. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66561. }
  66562. spaceMat.invertToRef(spaceMatInv);
  66563. var xzlen = null;
  66564. if (checkPitch) {
  66565. var localTarget = BoneLookController._tmpVecs[3];
  66566. target.subtractToRef(bonePos, localTarget);
  66567. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66568. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66569. var pitch = Math.atan2(localTarget.y, xzlen);
  66570. var newPitch = pitch;
  66571. if (pitch > this._maxPitch) {
  66572. localTarget.y = this._maxPitchTan * xzlen;
  66573. newPitch = this._maxPitch;
  66574. }
  66575. else if (pitch < this._minPitch) {
  66576. localTarget.y = this._minPitchTan * xzlen;
  66577. newPitch = this._minPitch;
  66578. }
  66579. if (pitch != newPitch) {
  66580. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66581. localTarget.addInPlace(bonePos);
  66582. target = localTarget;
  66583. }
  66584. }
  66585. if (checkYaw) {
  66586. var localTarget = BoneLookController._tmpVecs[4];
  66587. target.subtractToRef(bonePos, localTarget);
  66588. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66589. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66590. var newYaw = yaw;
  66591. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66592. if (xzlen == null) {
  66593. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66594. }
  66595. if (this._yawRange > Math.PI) {
  66596. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66597. localTarget.z = this._maxYawCos * xzlen;
  66598. localTarget.x = this._maxYawSin * xzlen;
  66599. newYaw = this._maxYaw;
  66600. }
  66601. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66602. localTarget.z = this._minYawCos * xzlen;
  66603. localTarget.x = this._minYawSin * xzlen;
  66604. newYaw = this._minYaw;
  66605. }
  66606. }
  66607. else {
  66608. if (yaw > this._maxYaw) {
  66609. localTarget.z = this._maxYawCos * xzlen;
  66610. localTarget.x = this._maxYawSin * xzlen;
  66611. newYaw = this._maxYaw;
  66612. }
  66613. else if (yaw < this._minYaw) {
  66614. localTarget.z = this._minYawCos * xzlen;
  66615. localTarget.x = this._minYawSin * xzlen;
  66616. newYaw = this._minYaw;
  66617. }
  66618. }
  66619. }
  66620. if (this._slerping && this._yawRange > Math.PI) {
  66621. //are we going to be crossing into the min/max region?
  66622. var boneFwd = BoneLookController._tmpVecs[8];
  66623. boneFwd.copyFrom(BABYLON.Axis.Z);
  66624. if (this._transformYawPitch) {
  66625. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66626. }
  66627. var boneRotMat = BoneLookController._tmpMats[4];
  66628. this._boneQuat.toRotationMatrix(boneRotMat);
  66629. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66630. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66631. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66632. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66633. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66634. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66635. if (angBtwTar > angBtwMidYaw) {
  66636. if (xzlen == null) {
  66637. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66638. }
  66639. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66640. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66641. if (angBtwMin < angBtwMax) {
  66642. newYaw = boneYaw + Math.PI * .75;
  66643. localTarget.z = Math.cos(newYaw) * xzlen;
  66644. localTarget.x = Math.sin(newYaw) * xzlen;
  66645. }
  66646. else {
  66647. newYaw = boneYaw - Math.PI * .75;
  66648. localTarget.z = Math.cos(newYaw) * xzlen;
  66649. localTarget.x = Math.sin(newYaw) * xzlen;
  66650. }
  66651. }
  66652. }
  66653. if (yaw != newYaw) {
  66654. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66655. localTarget.addInPlace(bonePos);
  66656. target = localTarget;
  66657. }
  66658. }
  66659. }
  66660. var zaxis = BoneLookController._tmpVecs[5];
  66661. var xaxis = BoneLookController._tmpVecs[6];
  66662. var yaxis = BoneLookController._tmpVecs[7];
  66663. var _tmpQuat = BoneLookController._tmpQuat;
  66664. target.subtractToRef(bonePos, zaxis);
  66665. zaxis.normalize();
  66666. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  66667. xaxis.normalize();
  66668. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  66669. yaxis.normalize();
  66670. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  66671. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  66672. return;
  66673. }
  66674. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  66675. return;
  66676. }
  66677. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  66678. return;
  66679. }
  66680. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  66681. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  66682. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  66683. }
  66684. if (this.slerpAmount < 1) {
  66685. if (!this._slerping) {
  66686. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  66687. }
  66688. if (this._transformYawPitch) {
  66689. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66690. }
  66691. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  66692. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  66693. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  66694. this._slerping = true;
  66695. }
  66696. else {
  66697. if (this._transformYawPitch) {
  66698. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66699. }
  66700. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  66701. this._slerping = false;
  66702. }
  66703. };
  66704. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  66705. var angDiff = ang2 - ang1;
  66706. angDiff %= Math.PI * 2;
  66707. if (angDiff > Math.PI) {
  66708. angDiff -= Math.PI * 2;
  66709. }
  66710. else if (angDiff < -Math.PI) {
  66711. angDiff += Math.PI * 2;
  66712. }
  66713. return angDiff;
  66714. };
  66715. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  66716. ang1 %= (2 * Math.PI);
  66717. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66718. ang2 %= (2 * Math.PI);
  66719. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66720. var ab = 0;
  66721. if (ang1 < ang2) {
  66722. ab = ang2 - ang1;
  66723. }
  66724. else {
  66725. ab = ang1 - ang2;
  66726. }
  66727. if (ab > Math.PI) {
  66728. ab = Math.PI * 2 - ab;
  66729. }
  66730. return ab;
  66731. };
  66732. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  66733. ang %= (2 * Math.PI);
  66734. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  66735. ang1 %= (2 * Math.PI);
  66736. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66737. ang2 %= (2 * Math.PI);
  66738. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66739. if (ang1 < ang2) {
  66740. if (ang > ang1 && ang < ang2) {
  66741. return true;
  66742. }
  66743. }
  66744. else {
  66745. if (ang > ang2 && ang < ang1) {
  66746. return true;
  66747. }
  66748. }
  66749. return false;
  66750. };
  66751. 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()];
  66752. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  66753. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66754. return BoneLookController;
  66755. }());
  66756. BABYLON.BoneLookController = BoneLookController;
  66757. })(BABYLON || (BABYLON = {}));
  66758. //# sourceMappingURL=babylon.boneLookController.js.map
  66759. var BABYLON;
  66760. (function (BABYLON) {
  66761. var Skeleton = /** @class */ (function () {
  66762. function Skeleton(name, id, scene) {
  66763. this.name = name;
  66764. this.id = id;
  66765. this.bones = new Array();
  66766. this.needInitialSkinMatrix = false;
  66767. this._isDirty = true;
  66768. this._meshesWithPoseMatrix = new Array();
  66769. this._identity = BABYLON.Matrix.Identity();
  66770. this._ranges = {};
  66771. this._lastAbsoluteTransformsUpdateId = -1;
  66772. // Events
  66773. /**
  66774. * An event triggered before computing the skeleton's matrices
  66775. * @type {BABYLON.Observable}
  66776. */
  66777. this.onBeforeComputeObservable = new BABYLON.Observable();
  66778. this.bones = [];
  66779. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66780. scene.skeletons.push(this);
  66781. //make sure it will recalculate the matrix next time prepare is called.
  66782. this._isDirty = true;
  66783. }
  66784. // Members
  66785. Skeleton.prototype.getTransformMatrices = function (mesh) {
  66786. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  66787. return mesh._bonesTransformMatrices;
  66788. }
  66789. if (!this._transformMatrices) {
  66790. this.prepare();
  66791. }
  66792. return this._transformMatrices;
  66793. };
  66794. Skeleton.prototype.getScene = function () {
  66795. return this._scene;
  66796. };
  66797. // Methods
  66798. /**
  66799. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  66800. */
  66801. Skeleton.prototype.toString = function (fullDetails) {
  66802. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  66803. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  66804. if (fullDetails) {
  66805. ret += ", Ranges: {";
  66806. var first = true;
  66807. for (var name_1 in this._ranges) {
  66808. if (first) {
  66809. ret += ", ";
  66810. first = false;
  66811. }
  66812. ret += name_1;
  66813. }
  66814. ret += "}";
  66815. }
  66816. return ret;
  66817. };
  66818. /**
  66819. * Get bone's index searching by name
  66820. * @param {string} name is bone's name to search for
  66821. * @return {number} Indice of the bone. Returns -1 if not found
  66822. */
  66823. Skeleton.prototype.getBoneIndexByName = function (name) {
  66824. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  66825. if (this.bones[boneIndex].name === name) {
  66826. return boneIndex;
  66827. }
  66828. }
  66829. return -1;
  66830. };
  66831. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  66832. // check name not already in use
  66833. if (!this._ranges[name]) {
  66834. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  66835. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66836. if (this.bones[i].animations[0]) {
  66837. this.bones[i].animations[0].createRange(name, from, to);
  66838. }
  66839. }
  66840. }
  66841. };
  66842. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  66843. if (deleteFrames === void 0) { deleteFrames = true; }
  66844. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66845. if (this.bones[i].animations[0]) {
  66846. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  66847. }
  66848. }
  66849. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  66850. };
  66851. Skeleton.prototype.getAnimationRange = function (name) {
  66852. return this._ranges[name];
  66853. };
  66854. /**
  66855. * Returns as an Array, all AnimationRanges defined on this skeleton
  66856. */
  66857. Skeleton.prototype.getAnimationRanges = function () {
  66858. var animationRanges = [];
  66859. var name;
  66860. var i = 0;
  66861. for (name in this._ranges) {
  66862. animationRanges[i] = this._ranges[name];
  66863. i++;
  66864. }
  66865. return animationRanges;
  66866. };
  66867. /**
  66868. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  66869. */
  66870. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  66871. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66872. if (this._ranges[name] || !source.getAnimationRange(name)) {
  66873. return false;
  66874. }
  66875. var ret = true;
  66876. var frameOffset = this._getHighestAnimationFrame() + 1;
  66877. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  66878. var boneDict = {};
  66879. var sourceBones = source.bones;
  66880. var nBones;
  66881. var i;
  66882. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  66883. boneDict[sourceBones[i].name] = sourceBones[i];
  66884. }
  66885. if (this.bones.length !== sourceBones.length) {
  66886. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  66887. ret = false;
  66888. }
  66889. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  66890. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  66891. var boneName = this.bones[i].name;
  66892. var sourceBone = boneDict[boneName];
  66893. if (sourceBone) {
  66894. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  66895. }
  66896. else {
  66897. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  66898. ret = false;
  66899. }
  66900. }
  66901. // do not call createAnimationRange(), since it also is done to bones, which was already done
  66902. var range = source.getAnimationRange(name);
  66903. if (range) {
  66904. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  66905. }
  66906. return ret;
  66907. };
  66908. Skeleton.prototype.returnToRest = function () {
  66909. for (var index = 0; index < this.bones.length; index++) {
  66910. this.bones[index].returnToRest();
  66911. }
  66912. };
  66913. Skeleton.prototype._getHighestAnimationFrame = function () {
  66914. var ret = 0;
  66915. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66916. if (this.bones[i].animations[0]) {
  66917. var highest = this.bones[i].animations[0].getHighestFrame();
  66918. if (ret < highest) {
  66919. ret = highest;
  66920. }
  66921. }
  66922. }
  66923. return ret;
  66924. };
  66925. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  66926. var range = this.getAnimationRange(name);
  66927. if (!range) {
  66928. return null;
  66929. }
  66930. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  66931. };
  66932. Skeleton.prototype._markAsDirty = function () {
  66933. this._isDirty = true;
  66934. };
  66935. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  66936. this._meshesWithPoseMatrix.push(mesh);
  66937. };
  66938. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  66939. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  66940. if (index > -1) {
  66941. this._meshesWithPoseMatrix.splice(index, 1);
  66942. }
  66943. };
  66944. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  66945. this.onBeforeComputeObservable.notifyObservers(this);
  66946. for (var index = 0; index < this.bones.length; index++) {
  66947. var bone = this.bones[index];
  66948. var parentBone = bone.getParent();
  66949. if (parentBone) {
  66950. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  66951. }
  66952. else {
  66953. if (initialSkinMatrix) {
  66954. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  66955. }
  66956. else {
  66957. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  66958. }
  66959. }
  66960. if (bone._index !== -1) {
  66961. var mappedIndex = bone._index === null ? index : bone._index;
  66962. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  66963. }
  66964. }
  66965. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  66966. };
  66967. Skeleton.prototype.prepare = function () {
  66968. if (!this._isDirty) {
  66969. return;
  66970. }
  66971. if (this.needInitialSkinMatrix) {
  66972. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  66973. var mesh = this._meshesWithPoseMatrix[index];
  66974. var poseMatrix = mesh.getPoseMatrix();
  66975. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  66976. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66977. }
  66978. if (this._synchronizedWithMesh !== mesh) {
  66979. this._synchronizedWithMesh = mesh;
  66980. // Prepare bones
  66981. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  66982. var bone = this.bones[boneIndex];
  66983. if (!bone.getParent()) {
  66984. var matrix = bone.getBaseMatrix();
  66985. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  66986. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  66987. }
  66988. }
  66989. }
  66990. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  66991. }
  66992. }
  66993. else {
  66994. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  66995. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  66996. }
  66997. this._computeTransformMatrices(this._transformMatrices, null);
  66998. }
  66999. this._isDirty = false;
  67000. this._scene._activeBones.addCount(this.bones.length, false);
  67001. };
  67002. Skeleton.prototype.getAnimatables = function () {
  67003. if (!this._animatables || this._animatables.length !== this.bones.length) {
  67004. this._animatables = [];
  67005. for (var index = 0; index < this.bones.length; index++) {
  67006. this._animatables.push(this.bones[index]);
  67007. }
  67008. }
  67009. return this._animatables;
  67010. };
  67011. Skeleton.prototype.clone = function (name, id) {
  67012. var result = new Skeleton(name, id || name, this._scene);
  67013. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67014. for (var index = 0; index < this.bones.length; index++) {
  67015. var source = this.bones[index];
  67016. var parentBone = null;
  67017. var parent_1 = source.getParent();
  67018. if (parent_1) {
  67019. var parentIndex = this.bones.indexOf(parent_1);
  67020. parentBone = result.bones[parentIndex];
  67021. }
  67022. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  67023. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  67024. }
  67025. if (this._ranges) {
  67026. result._ranges = {};
  67027. for (var rangeName in this._ranges) {
  67028. var range = this._ranges[rangeName];
  67029. if (range) {
  67030. result._ranges[rangeName] = range.clone();
  67031. }
  67032. }
  67033. }
  67034. this._isDirty = true;
  67035. return result;
  67036. };
  67037. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  67038. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  67039. this.bones.forEach(function (bone) {
  67040. bone.animations.forEach(function (animation) {
  67041. animation.enableBlending = true;
  67042. animation.blendingSpeed = blendingSpeed;
  67043. });
  67044. });
  67045. };
  67046. Skeleton.prototype.dispose = function () {
  67047. this._meshesWithPoseMatrix = [];
  67048. // Animations
  67049. this.getScene().stopAnimation(this);
  67050. // Remove from scene
  67051. this.getScene().removeSkeleton(this);
  67052. };
  67053. Skeleton.prototype.serialize = function () {
  67054. var serializationObject = {};
  67055. serializationObject.name = this.name;
  67056. serializationObject.id = this.id;
  67057. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  67058. serializationObject.bones = [];
  67059. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67060. for (var index = 0; index < this.bones.length; index++) {
  67061. var bone = this.bones[index];
  67062. var parent_2 = bone.getParent();
  67063. var serializedBone = {
  67064. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  67065. name: bone.name,
  67066. matrix: bone.getBaseMatrix().toArray(),
  67067. rest: bone.getRestPose().toArray()
  67068. };
  67069. serializationObject.bones.push(serializedBone);
  67070. if (bone.length) {
  67071. serializedBone.length = bone.length;
  67072. }
  67073. if (bone.animations && bone.animations.length > 0) {
  67074. serializedBone.animation = bone.animations[0].serialize();
  67075. }
  67076. serializationObject.ranges = [];
  67077. for (var name in this._ranges) {
  67078. var source = this._ranges[name];
  67079. if (!source) {
  67080. continue;
  67081. }
  67082. var range = {};
  67083. range.name = name;
  67084. range.from = source.from;
  67085. range.to = source.to;
  67086. serializationObject.ranges.push(range);
  67087. }
  67088. }
  67089. return serializationObject;
  67090. };
  67091. Skeleton.Parse = function (parsedSkeleton, scene) {
  67092. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  67093. if (parsedSkeleton.dimensionsAtRest) {
  67094. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  67095. }
  67096. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  67097. var index;
  67098. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  67099. var parsedBone = parsedSkeleton.bones[index];
  67100. var parentBone = null;
  67101. if (parsedBone.parentBoneIndex > -1) {
  67102. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  67103. }
  67104. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  67105. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  67106. if (parsedBone.length) {
  67107. bone.length = parsedBone.length;
  67108. }
  67109. if (parsedBone.animation) {
  67110. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  67111. }
  67112. }
  67113. // placed after bones, so createAnimationRange can cascade down
  67114. if (parsedSkeleton.ranges) {
  67115. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  67116. var data = parsedSkeleton.ranges[index];
  67117. skeleton.createAnimationRange(data.name, data.from, data.to);
  67118. }
  67119. }
  67120. return skeleton;
  67121. };
  67122. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  67123. if (forceUpdate === void 0) { forceUpdate = false; }
  67124. var renderId = this._scene.getRenderId();
  67125. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  67126. this.bones[0].computeAbsoluteTransforms();
  67127. this._lastAbsoluteTransformsUpdateId = renderId;
  67128. }
  67129. };
  67130. Skeleton.prototype.getPoseMatrix = function () {
  67131. var poseMatrix = null;
  67132. if (this._meshesWithPoseMatrix.length > 0) {
  67133. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  67134. }
  67135. return poseMatrix;
  67136. };
  67137. Skeleton.prototype.sortBones = function () {
  67138. var bones = new Array();
  67139. var visited = new Array(this.bones.length);
  67140. for (var index = 0; index < this.bones.length; index++) {
  67141. this._sortBones(index, bones, visited);
  67142. }
  67143. this.bones = bones;
  67144. };
  67145. Skeleton.prototype._sortBones = function (index, bones, visited) {
  67146. if (visited[index]) {
  67147. return;
  67148. }
  67149. visited[index] = true;
  67150. var bone = this.bones[index];
  67151. if (bone._index === undefined) {
  67152. bone._index = index;
  67153. }
  67154. var parentBone = bone.getParent();
  67155. if (parentBone) {
  67156. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  67157. }
  67158. bones.push(bone);
  67159. };
  67160. return Skeleton;
  67161. }());
  67162. BABYLON.Skeleton = Skeleton;
  67163. })(BABYLON || (BABYLON = {}));
  67164. //# sourceMappingURL=babylon.skeleton.js.map
  67165. var BABYLON;
  67166. (function (BABYLON) {
  67167. var SphericalPolynomial = /** @class */ (function () {
  67168. function SphericalPolynomial() {
  67169. this.x = BABYLON.Vector3.Zero();
  67170. this.y = BABYLON.Vector3.Zero();
  67171. this.z = BABYLON.Vector3.Zero();
  67172. this.xx = BABYLON.Vector3.Zero();
  67173. this.yy = BABYLON.Vector3.Zero();
  67174. this.zz = BABYLON.Vector3.Zero();
  67175. this.xy = BABYLON.Vector3.Zero();
  67176. this.yz = BABYLON.Vector3.Zero();
  67177. this.zx = BABYLON.Vector3.Zero();
  67178. }
  67179. SphericalPolynomial.prototype.addAmbient = function (color) {
  67180. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67181. this.xx = this.xx.add(colorVector);
  67182. this.yy = this.yy.add(colorVector);
  67183. this.zz = this.zz.add(colorVector);
  67184. };
  67185. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  67186. var result = new SphericalPolynomial();
  67187. result.x = harmonics.L11.scale(1.02333);
  67188. result.y = harmonics.L1_1.scale(1.02333);
  67189. result.z = harmonics.L10.scale(1.02333);
  67190. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  67191. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  67192. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  67193. result.yz = harmonics.L2_1.scale(0.858086);
  67194. result.zx = harmonics.L21.scale(0.858086);
  67195. result.xy = harmonics.L2_2.scale(0.858086);
  67196. result.scale(1.0 / Math.PI);
  67197. return result;
  67198. };
  67199. SphericalPolynomial.prototype.scale = function (scale) {
  67200. this.x = this.x.scale(scale);
  67201. this.y = this.y.scale(scale);
  67202. this.z = this.z.scale(scale);
  67203. this.xx = this.xx.scale(scale);
  67204. this.yy = this.yy.scale(scale);
  67205. this.zz = this.zz.scale(scale);
  67206. this.yz = this.yz.scale(scale);
  67207. this.zx = this.zx.scale(scale);
  67208. this.xy = this.xy.scale(scale);
  67209. };
  67210. return SphericalPolynomial;
  67211. }());
  67212. BABYLON.SphericalPolynomial = SphericalPolynomial;
  67213. var SphericalHarmonics = /** @class */ (function () {
  67214. function SphericalHarmonics() {
  67215. this.L00 = BABYLON.Vector3.Zero();
  67216. this.L1_1 = BABYLON.Vector3.Zero();
  67217. this.L10 = BABYLON.Vector3.Zero();
  67218. this.L11 = BABYLON.Vector3.Zero();
  67219. this.L2_2 = BABYLON.Vector3.Zero();
  67220. this.L2_1 = BABYLON.Vector3.Zero();
  67221. this.L20 = BABYLON.Vector3.Zero();
  67222. this.L21 = BABYLON.Vector3.Zero();
  67223. this.L22 = BABYLON.Vector3.Zero();
  67224. }
  67225. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  67226. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67227. var c = colorVector.scale(deltaSolidAngle);
  67228. this.L00 = this.L00.add(c.scale(0.282095));
  67229. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  67230. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  67231. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  67232. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  67233. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  67234. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  67235. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  67236. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  67237. };
  67238. SphericalHarmonics.prototype.scale = function (scale) {
  67239. this.L00 = this.L00.scale(scale);
  67240. this.L1_1 = this.L1_1.scale(scale);
  67241. this.L10 = this.L10.scale(scale);
  67242. this.L11 = this.L11.scale(scale);
  67243. this.L2_2 = this.L2_2.scale(scale);
  67244. this.L2_1 = this.L2_1.scale(scale);
  67245. this.L20 = this.L20.scale(scale);
  67246. this.L21 = this.L21.scale(scale);
  67247. this.L22 = this.L22.scale(scale);
  67248. };
  67249. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  67250. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  67251. //
  67252. // E_lm = A_l * L_lm
  67253. //
  67254. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  67255. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  67256. // the scaling factors are given in equation 9.
  67257. // Constant (Band 0)
  67258. this.L00 = this.L00.scale(3.141593);
  67259. // Linear (Band 1)
  67260. this.L1_1 = this.L1_1.scale(2.094395);
  67261. this.L10 = this.L10.scale(2.094395);
  67262. this.L11 = this.L11.scale(2.094395);
  67263. // Quadratic (Band 2)
  67264. this.L2_2 = this.L2_2.scale(0.785398);
  67265. this.L2_1 = this.L2_1.scale(0.785398);
  67266. this.L20 = this.L20.scale(0.785398);
  67267. this.L21 = this.L21.scale(0.785398);
  67268. this.L22 = this.L22.scale(0.785398);
  67269. };
  67270. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  67271. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  67272. // L = (1/pi) * E * rho
  67273. //
  67274. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  67275. this.scale(1.0 / Math.PI);
  67276. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  67277. // (The pixel shader must apply albedo after texture fetches, etc).
  67278. };
  67279. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  67280. var result = new SphericalHarmonics();
  67281. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  67282. result.L1_1 = polynomial.y.scale(0.977204);
  67283. result.L10 = polynomial.z.scale(0.977204);
  67284. result.L11 = polynomial.x.scale(0.977204);
  67285. result.L2_2 = polynomial.xy.scale(1.16538);
  67286. result.L2_1 = polynomial.yz.scale(1.16538);
  67287. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  67288. result.L21 = polynomial.zx.scale(1.16538);
  67289. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  67290. result.scale(Math.PI);
  67291. return result;
  67292. };
  67293. return SphericalHarmonics;
  67294. }());
  67295. BABYLON.SphericalHarmonics = SphericalHarmonics;
  67296. })(BABYLON || (BABYLON = {}));
  67297. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  67298. var BABYLON;
  67299. (function (BABYLON) {
  67300. var FileFaceOrientation = /** @class */ (function () {
  67301. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  67302. this.name = name;
  67303. this.worldAxisForNormal = worldAxisForNormal;
  67304. this.worldAxisForFileX = worldAxisForFileX;
  67305. this.worldAxisForFileY = worldAxisForFileY;
  67306. }
  67307. return FileFaceOrientation;
  67308. }());
  67309. ;
  67310. /**
  67311. * Helper class dealing with the extraction of spherical polynomial dataArray
  67312. * from a cube map.
  67313. */
  67314. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  67315. function CubeMapToSphericalPolynomialTools() {
  67316. }
  67317. /**
  67318. * Converts a texture to the according Spherical Polynomial data.
  67319. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67320. *
  67321. * @param texture The texture to extract the information from.
  67322. * @return The Spherical Polynomial data.
  67323. */
  67324. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  67325. if (!texture.isCube) {
  67326. // Only supports cube Textures currently.
  67327. return null;
  67328. }
  67329. var size = texture.getSize().width;
  67330. var right = texture.readPixels(0);
  67331. var left = texture.readPixels(1);
  67332. var up;
  67333. var down;
  67334. if (texture.isRenderTarget) {
  67335. up = texture.readPixels(3);
  67336. down = texture.readPixels(2);
  67337. }
  67338. else {
  67339. up = texture.readPixels(2);
  67340. down = texture.readPixels(3);
  67341. }
  67342. var front = texture.readPixels(4);
  67343. var back = texture.readPixels(5);
  67344. var gammaSpace = texture.gammaSpace;
  67345. // Always read as RGBA.
  67346. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  67347. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67348. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67349. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67350. }
  67351. var cubeInfo = {
  67352. size: size,
  67353. right: right,
  67354. left: left,
  67355. up: up,
  67356. down: down,
  67357. front: front,
  67358. back: back,
  67359. format: format,
  67360. type: type,
  67361. gammaSpace: gammaSpace,
  67362. };
  67363. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  67364. };
  67365. /**
  67366. * Converts a cubemap to the according Spherical Polynomial data.
  67367. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67368. *
  67369. * @param cubeInfo The Cube map to extract the information from.
  67370. * @return The Spherical Polynomial data.
  67371. */
  67372. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  67373. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  67374. var totalSolidAngle = 0.0;
  67375. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  67376. var du = 2.0 / cubeInfo.size;
  67377. var dv = du;
  67378. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  67379. var minUV = du * 0.5 - 1.0;
  67380. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67381. var fileFace = this.FileFaces[faceIndex];
  67382. var dataArray = cubeInfo[fileFace.name];
  67383. var v = minUV;
  67384. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  67385. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  67386. // Because SP is still linear, so summation is fine in that basis.
  67387. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  67388. for (var y = 0; y < cubeInfo.size; y++) {
  67389. var u = minUV;
  67390. for (var x = 0; x < cubeInfo.size; x++) {
  67391. // World direction (not normalised)
  67392. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  67393. worldDirection.normalize();
  67394. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  67395. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  67396. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  67397. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  67398. // Handle Integer types.
  67399. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67400. r /= 255;
  67401. g /= 255;
  67402. b /= 255;
  67403. }
  67404. // Handle Gamma space textures.
  67405. if (cubeInfo.gammaSpace) {
  67406. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  67407. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  67408. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  67409. }
  67410. var color = new BABYLON.Color3(r, g, b);
  67411. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  67412. totalSolidAngle += deltaSolidAngle;
  67413. u += du;
  67414. }
  67415. v += dv;
  67416. }
  67417. }
  67418. // Solid angle for entire sphere is 4*pi
  67419. var sphereSolidAngle = 4.0 * Math.PI;
  67420. // Adjust the solid angle to allow for how many faces we processed.
  67421. var facesProcessed = 6.0;
  67422. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  67423. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  67424. // This is needed because the numerical integration over the cube uses a
  67425. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  67426. // and also to compensate for accumulative error due to float precision in the summation.
  67427. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  67428. sphericalHarmonics.scale(correctionFactor);
  67429. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  67430. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  67431. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  67432. };
  67433. CubeMapToSphericalPolynomialTools.FileFaces = [
  67434. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67435. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67436. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67437. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67438. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67439. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67440. ];
  67441. return CubeMapToSphericalPolynomialTools;
  67442. }());
  67443. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67444. })(BABYLON || (BABYLON = {}));
  67445. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67446. var BABYLON;
  67447. (function (BABYLON) {
  67448. /**
  67449. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67450. */
  67451. var PanoramaToCubeMapTools = /** @class */ (function () {
  67452. function PanoramaToCubeMapTools() {
  67453. }
  67454. /**
  67455. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67456. *
  67457. * @param float32Array The source data.
  67458. * @param inputWidth The width of the input panorama.
  67459. * @param inputhHeight The height of the input panorama.
  67460. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67461. * @return The cubemap data
  67462. */
  67463. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67464. if (!float32Array) {
  67465. throw "ConvertPanoramaToCubemap: input cannot be null";
  67466. }
  67467. if (float32Array.length != inputWidth * inputHeight * 3) {
  67468. throw "ConvertPanoramaToCubemap: input size is wrong";
  67469. }
  67470. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67471. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67472. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67473. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67474. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67475. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67476. return {
  67477. front: textureFront,
  67478. back: textureBack,
  67479. left: textureLeft,
  67480. right: textureRight,
  67481. up: textureUp,
  67482. down: textureDown,
  67483. size: size,
  67484. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67485. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67486. gammaSpace: false,
  67487. };
  67488. };
  67489. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67490. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67491. var textureArray = new Float32Array(buffer);
  67492. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67493. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67494. var dy = 1 / texSize;
  67495. var fy = 0;
  67496. for (var y = 0; y < texSize; y++) {
  67497. var xv1 = faceData[0];
  67498. var xv2 = faceData[2];
  67499. for (var x = 0; x < texSize; x++) {
  67500. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67501. v.normalize();
  67502. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67503. // 3 channels per pixels
  67504. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67505. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67506. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67507. xv1 = xv1.add(rotDX1);
  67508. xv2 = xv2.add(rotDX2);
  67509. }
  67510. fy += dy;
  67511. }
  67512. return textureArray;
  67513. };
  67514. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67515. var theta = Math.atan2(vDir.z, vDir.x);
  67516. var phi = Math.acos(vDir.y);
  67517. while (theta < -Math.PI)
  67518. theta += 2 * Math.PI;
  67519. while (theta > Math.PI)
  67520. theta -= 2 * Math.PI;
  67521. var dx = theta / Math.PI;
  67522. var dy = phi / Math.PI;
  67523. // recenter.
  67524. dx = dx * 0.5 + 0.5;
  67525. var px = Math.round(dx * inputWidth);
  67526. if (px < 0)
  67527. px = 0;
  67528. else if (px >= inputWidth)
  67529. px = inputWidth - 1;
  67530. var py = Math.round(dy * inputHeight);
  67531. if (py < 0)
  67532. py = 0;
  67533. else if (py >= inputHeight)
  67534. py = inputHeight - 1;
  67535. var inputY = (inputHeight - py - 1);
  67536. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67537. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67538. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67539. return {
  67540. r: r,
  67541. g: g,
  67542. b: b
  67543. };
  67544. };
  67545. PanoramaToCubeMapTools.FACE_FRONT = [
  67546. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67547. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67548. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67549. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67550. ];
  67551. PanoramaToCubeMapTools.FACE_BACK = [
  67552. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67553. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67554. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67555. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67556. ];
  67557. PanoramaToCubeMapTools.FACE_RIGHT = [
  67558. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67559. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67560. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67561. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67562. ];
  67563. PanoramaToCubeMapTools.FACE_LEFT = [
  67564. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67565. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67566. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67567. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67568. ];
  67569. PanoramaToCubeMapTools.FACE_DOWN = [
  67570. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67571. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67572. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67573. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67574. ];
  67575. PanoramaToCubeMapTools.FACE_UP = [
  67576. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67577. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67578. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67579. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67580. ];
  67581. return PanoramaToCubeMapTools;
  67582. }());
  67583. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67584. })(BABYLON || (BABYLON = {}));
  67585. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67586. var BABYLON;
  67587. (function (BABYLON) {
  67588. ;
  67589. /**
  67590. * This groups tools to convert HDR texture to native colors array.
  67591. */
  67592. var HDRTools = /** @class */ (function () {
  67593. function HDRTools() {
  67594. }
  67595. HDRTools.Ldexp = function (mantissa, exponent) {
  67596. if (exponent > 1023) {
  67597. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67598. }
  67599. if (exponent < -1074) {
  67600. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67601. }
  67602. return mantissa * Math.pow(2, exponent);
  67603. };
  67604. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67605. if (exponent > 0) {
  67606. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67607. float32array[index + 0] = red * exponent;
  67608. float32array[index + 1] = green * exponent;
  67609. float32array[index + 2] = blue * exponent;
  67610. }
  67611. else {
  67612. float32array[index + 0] = 0;
  67613. float32array[index + 1] = 0;
  67614. float32array[index + 2] = 0;
  67615. }
  67616. };
  67617. HDRTools.readStringLine = function (uint8array, startIndex) {
  67618. var line = "";
  67619. var character = "";
  67620. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67621. character = String.fromCharCode(uint8array[i]);
  67622. if (character == "\n") {
  67623. break;
  67624. }
  67625. line += character;
  67626. }
  67627. return line;
  67628. };
  67629. /**
  67630. * Reads header information from an RGBE texture stored in a native array.
  67631. * More information on this format are available here:
  67632. * https://en.wikipedia.org/wiki/RGBE_image_format
  67633. *
  67634. * @param uint8array The binary file stored in native array.
  67635. * @return The header information.
  67636. */
  67637. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67638. var height = 0;
  67639. var width = 0;
  67640. var line = this.readStringLine(uint8array, 0);
  67641. if (line[0] != '#' || line[1] != '?') {
  67642. throw "Bad HDR Format.";
  67643. }
  67644. var endOfHeader = false;
  67645. var findFormat = false;
  67646. var lineIndex = 0;
  67647. do {
  67648. lineIndex += (line.length + 1);
  67649. line = this.readStringLine(uint8array, lineIndex);
  67650. if (line == "FORMAT=32-bit_rle_rgbe") {
  67651. findFormat = true;
  67652. }
  67653. else if (line.length == 0) {
  67654. endOfHeader = true;
  67655. }
  67656. } while (!endOfHeader);
  67657. if (!findFormat) {
  67658. throw "HDR Bad header format, unsupported FORMAT";
  67659. }
  67660. lineIndex += (line.length + 1);
  67661. line = this.readStringLine(uint8array, lineIndex);
  67662. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67663. var match = sizeRegexp.exec(line);
  67664. // TODO. Support +Y and -X if needed.
  67665. if (!match || match.length < 3) {
  67666. throw "HDR Bad header format, no size";
  67667. }
  67668. width = parseInt(match[2]);
  67669. height = parseInt(match[1]);
  67670. if (width < 8 || width > 0x7fff) {
  67671. throw "HDR Bad header format, unsupported size";
  67672. }
  67673. lineIndex += (line.length + 1);
  67674. return {
  67675. height: height,
  67676. width: width,
  67677. dataPosition: lineIndex
  67678. };
  67679. };
  67680. /**
  67681. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  67682. * This RGBE texture needs to store the information as a panorama.
  67683. *
  67684. * More information on this format are available here:
  67685. * https://en.wikipedia.org/wiki/RGBE_image_format
  67686. *
  67687. * @param buffer The binary file stored in an array buffer.
  67688. * @param size The expected size of the extracted cubemap.
  67689. * @return The Cube Map information.
  67690. */
  67691. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  67692. var uint8array = new Uint8Array(buffer);
  67693. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  67694. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67695. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  67696. return cubeMapData;
  67697. };
  67698. /**
  67699. * Returns the pixels data extracted from an RGBE texture.
  67700. * This pixels will be stored left to right up to down in the R G B order in one array.
  67701. *
  67702. * More information on this format are available here:
  67703. * https://en.wikipedia.org/wiki/RGBE_image_format
  67704. *
  67705. * @param uint8array The binary file stored in an array buffer.
  67706. * @param hdrInfo The header information of the file.
  67707. * @return The pixels data in RGB right to left up to down order.
  67708. */
  67709. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  67710. // Keep for multi format supports.
  67711. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67712. };
  67713. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  67714. var num_scanlines = hdrInfo.height;
  67715. var scanline_width = hdrInfo.width;
  67716. var a, b, c, d, count;
  67717. var dataIndex = hdrInfo.dataPosition;
  67718. var index = 0, endIndex = 0, i = 0;
  67719. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  67720. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  67721. // 3 channels of 4 bytes per pixel in float.
  67722. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  67723. var resultArray = new Float32Array(resultBuffer);
  67724. // read in each successive scanline
  67725. while (num_scanlines > 0) {
  67726. a = uint8array[dataIndex++];
  67727. b = uint8array[dataIndex++];
  67728. c = uint8array[dataIndex++];
  67729. d = uint8array[dataIndex++];
  67730. if (a != 2 || b != 2 || (c & 0x80)) {
  67731. // this file is not run length encoded
  67732. throw "HDR Bad header format, not RLE";
  67733. }
  67734. if (((c << 8) | d) != scanline_width) {
  67735. throw "HDR Bad header format, wrong scan line width";
  67736. }
  67737. index = 0;
  67738. // read each of the four channels for the scanline into the buffer
  67739. for (i = 0; i < 4; i++) {
  67740. endIndex = (i + 1) * scanline_width;
  67741. while (index < endIndex) {
  67742. a = uint8array[dataIndex++];
  67743. b = uint8array[dataIndex++];
  67744. if (a > 128) {
  67745. // a run of the same value
  67746. count = a - 128;
  67747. if ((count == 0) || (count > endIndex - index)) {
  67748. throw "HDR Bad Format, bad scanline data (run)";
  67749. }
  67750. while (count-- > 0) {
  67751. scanLineArray[index++] = b;
  67752. }
  67753. }
  67754. else {
  67755. // a non-run
  67756. count = a;
  67757. if ((count == 0) || (count > endIndex - index)) {
  67758. throw "HDR Bad Format, bad scanline data (non-run)";
  67759. }
  67760. scanLineArray[index++] = b;
  67761. if (--count > 0) {
  67762. for (var j = 0; j < count; j++) {
  67763. scanLineArray[index++] = uint8array[dataIndex++];
  67764. }
  67765. }
  67766. }
  67767. }
  67768. }
  67769. // now convert data from buffer into floats
  67770. for (i = 0; i < scanline_width; i++) {
  67771. a = scanLineArray[i];
  67772. b = scanLineArray[i + scanline_width];
  67773. c = scanLineArray[i + 2 * scanline_width];
  67774. d = scanLineArray[i + 3 * scanline_width];
  67775. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  67776. }
  67777. num_scanlines--;
  67778. }
  67779. return resultArray;
  67780. };
  67781. return HDRTools;
  67782. }());
  67783. BABYLON.HDRTools = HDRTools;
  67784. })(BABYLON || (BABYLON = {}));
  67785. //# sourceMappingURL=babylon.hdr.js.map
  67786. var BABYLON;
  67787. (function (BABYLON) {
  67788. /**
  67789. * This represents a texture coming from an HDR input.
  67790. *
  67791. * The only supported format is currently panorama picture stored in RGBE format.
  67792. * Example of such files can be found on HDRLib: http://hdrlib.com/
  67793. */
  67794. var HDRCubeTexture = /** @class */ (function (_super) {
  67795. __extends(HDRCubeTexture, _super);
  67796. /**
  67797. * Instantiates an HDRTexture from the following parameters.
  67798. *
  67799. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  67800. * @param scene The scene the texture will be used in
  67801. * @param size The cubemap 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.
  67802. * @param noMipmap Forces to not generate the mipmap if true
  67803. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  67804. * @param useInGammaSpace 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)
  67805. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  67806. */
  67807. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  67808. if (noMipmap === void 0) { noMipmap = false; }
  67809. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67810. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67811. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67812. if (onLoad === void 0) { onLoad = null; }
  67813. if (onError === void 0) { onError = null; }
  67814. var _this = _super.call(this, scene) || this;
  67815. _this._useInGammaSpace = false;
  67816. _this._generateHarmonics = true;
  67817. _this._isBABYLONPreprocessed = false;
  67818. _this._onLoad = null;
  67819. _this._onError = null;
  67820. /**
  67821. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  67822. */
  67823. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67824. /**
  67825. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  67826. * This is usefull at run time to apply the good shader.
  67827. */
  67828. _this.isPMREM = false;
  67829. _this._isBlocking = true;
  67830. if (!url) {
  67831. return _this;
  67832. }
  67833. _this.name = url;
  67834. _this.url = url;
  67835. _this.hasAlpha = false;
  67836. _this.isCube = true;
  67837. _this._textureMatrix = BABYLON.Matrix.Identity();
  67838. _this._onLoad = onLoad;
  67839. _this._onError = onError;
  67840. _this.gammaSpace = false;
  67841. var caps = scene.getEngine().getCaps();
  67842. if (size) {
  67843. _this._isBABYLONPreprocessed = false;
  67844. _this._noMipmap = noMipmap;
  67845. _this._size = size;
  67846. _this._useInGammaSpace = useInGammaSpace;
  67847. _this._usePMREMGenerator = usePMREMGenerator &&
  67848. caps.textureLOD &&
  67849. caps.textureFloat &&
  67850. !_this._useInGammaSpace;
  67851. }
  67852. else {
  67853. _this._isBABYLONPreprocessed = true;
  67854. _this._noMipmap = false;
  67855. _this._useInGammaSpace = false;
  67856. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  67857. !_this._useInGammaSpace;
  67858. }
  67859. _this.isPMREM = _this._usePMREMGenerator;
  67860. _this._texture = _this._getFromCache(url, _this._noMipmap);
  67861. if (!_this._texture) {
  67862. if (!scene.useDelayedTextureLoading) {
  67863. _this.loadTexture();
  67864. }
  67865. else {
  67866. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67867. }
  67868. }
  67869. return _this;
  67870. }
  67871. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  67872. /**
  67873. * Gets wether or not the texture is blocking during loading.
  67874. */
  67875. get: function () {
  67876. return this._isBlocking;
  67877. },
  67878. /**
  67879. * Sets wether or not the texture is blocking during loading.
  67880. */
  67881. set: function (value) {
  67882. this._isBlocking = value;
  67883. },
  67884. enumerable: true,
  67885. configurable: true
  67886. });
  67887. /**
  67888. * Occurs when the file is a preprocessed .babylon.hdr file.
  67889. */
  67890. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  67891. var _this = this;
  67892. var mipLevels = 0;
  67893. var floatArrayView = null;
  67894. var scene = this.getScene();
  67895. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  67896. var mips = new Array();
  67897. if (!floatArrayView) {
  67898. return mips;
  67899. }
  67900. var startIndex = 30;
  67901. for (var level = 0; level < mipLevels; level++) {
  67902. mips.push([]);
  67903. // Fill each pixel of the mip level.
  67904. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  67905. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67906. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  67907. mips[level].push(faceData);
  67908. startIndex += faceSize;
  67909. }
  67910. }
  67911. return mips;
  67912. } : null;
  67913. var callback = function (buffer) {
  67914. var scene = _this.getScene();
  67915. if (!scene) {
  67916. return null;
  67917. }
  67918. // Create Native Array Views
  67919. var intArrayView = new Int32Array(buffer);
  67920. floatArrayView = new Float32Array(buffer);
  67921. // Fill header.
  67922. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  67923. _this._size = intArrayView[1]; // CubeMap max mip face size.
  67924. // Update Texture Information.
  67925. if (!_this._texture) {
  67926. return null;
  67927. }
  67928. _this._texture.updateSize(_this._size, _this._size);
  67929. // Fill polynomial information.
  67930. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  67931. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  67932. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  67933. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  67934. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  67935. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  67936. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  67937. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  67938. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  67939. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  67940. _this.sphericalPolynomial = sphericalPolynomial;
  67941. // Fill pixel data.
  67942. mipLevels = intArrayView[29]; // Number of mip levels.
  67943. var startIndex = 30;
  67944. var data = [];
  67945. var faceSize = Math.pow(_this._size, 2) * 3;
  67946. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67947. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  67948. startIndex += faceSize;
  67949. }
  67950. var results = [];
  67951. var byteArray = null;
  67952. // Push each faces.
  67953. for (var k = 0; k < 6; k++) {
  67954. var dataFace = null;
  67955. // To be deprecated.
  67956. if (version === 1) {
  67957. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  67958. dataFace = data[j];
  67959. }
  67960. // If special cases.
  67961. if (!mipmapGenerator && dataFace) {
  67962. if (!scene.getEngine().getCaps().textureFloat) {
  67963. // 3 channels of 1 bytes per pixel in bytes.
  67964. var byteBuffer = new ArrayBuffer(faceSize);
  67965. byteArray = new Uint8Array(byteBuffer);
  67966. }
  67967. for (var i = 0; i < _this._size * _this._size; i++) {
  67968. // Put in gamma space if requested.
  67969. if (_this._useInGammaSpace) {
  67970. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  67971. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  67972. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  67973. }
  67974. // Convert to int texture for fallback.
  67975. if (byteArray) {
  67976. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  67977. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  67978. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  67979. // May use luminance instead if the result is not accurate.
  67980. var max = Math.max(Math.max(r, g), b);
  67981. if (max > 255) {
  67982. var scale = 255 / max;
  67983. r *= scale;
  67984. g *= scale;
  67985. b *= scale;
  67986. }
  67987. byteArray[(i * 3) + 0] = r;
  67988. byteArray[(i * 3) + 1] = g;
  67989. byteArray[(i * 3) + 2] = b;
  67990. }
  67991. }
  67992. }
  67993. // Fill the array accordingly.
  67994. if (byteArray) {
  67995. results.push(byteArray);
  67996. }
  67997. else {
  67998. results.push(dataFace);
  67999. }
  68000. }
  68001. return results;
  68002. };
  68003. if (scene) {
  68004. 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, mipmapGenerator, this._onLoad, this._onError);
  68005. }
  68006. };
  68007. /**
  68008. * Occurs when the file is raw .hdr file.
  68009. */
  68010. HDRCubeTexture.prototype.loadHDRTexture = function () {
  68011. var _this = this;
  68012. var callback = function (buffer) {
  68013. var scene = _this.getScene();
  68014. if (!scene) {
  68015. return null;
  68016. }
  68017. // Extract the raw linear data.
  68018. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  68019. // Generate harmonics if needed.
  68020. if (_this._generateHarmonics) {
  68021. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  68022. _this.sphericalPolynomial = sphericalPolynomial;
  68023. }
  68024. var results = [];
  68025. var byteArray = null;
  68026. // Push each faces.
  68027. for (var j = 0; j < 6; j++) {
  68028. // Create uintarray fallback.
  68029. if (!scene.getEngine().getCaps().textureFloat) {
  68030. // 3 channels of 1 bytes per pixel in bytes.
  68031. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  68032. byteArray = new Uint8Array(byteBuffer);
  68033. }
  68034. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  68035. // If special cases.
  68036. if (_this._useInGammaSpace || byteArray) {
  68037. for (var i = 0; i < _this._size * _this._size; i++) {
  68038. // Put in gamma space if requested.
  68039. if (_this._useInGammaSpace) {
  68040. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68041. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68042. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68043. }
  68044. // Convert to int texture for fallback.
  68045. if (byteArray) {
  68046. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68047. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68048. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68049. // May use luminance instead if the result is not accurate.
  68050. var max = Math.max(Math.max(r, g), b);
  68051. if (max > 255) {
  68052. var scale = 255 / max;
  68053. r *= scale;
  68054. g *= scale;
  68055. b *= scale;
  68056. }
  68057. byteArray[(i * 3) + 0] = r;
  68058. byteArray[(i * 3) + 1] = g;
  68059. byteArray[(i * 3) + 2] = b;
  68060. }
  68061. }
  68062. }
  68063. if (byteArray) {
  68064. results.push(byteArray);
  68065. }
  68066. else {
  68067. results.push(dataFace);
  68068. }
  68069. }
  68070. return results;
  68071. };
  68072. var mipmapGenerator = null;
  68073. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  68074. // if (!this._noMipmap &&
  68075. // this._usePMREMGenerator) {
  68076. // mipmapGenerator = (data: ArrayBufferView[]) => {
  68077. // // Custom setup of the generator matching with the PBR shader values.
  68078. // var generator = new BABYLON.PMREMGenerator(data,
  68079. // this._size,
  68080. // this._size,
  68081. // 0,
  68082. // 3,
  68083. // this.getScene().getEngine().getCaps().textureFloat,
  68084. // 2048,
  68085. // 0.25,
  68086. // false,
  68087. // true);
  68088. // return generator.filterCubeMap();
  68089. // };
  68090. // }
  68091. var scene = this.getScene();
  68092. if (scene) {
  68093. 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, mipmapGenerator, this._onLoad, this._onError);
  68094. }
  68095. };
  68096. /**
  68097. * Starts the loading process of the texture.
  68098. */
  68099. HDRCubeTexture.prototype.loadTexture = function () {
  68100. if (this._isBABYLONPreprocessed) {
  68101. this.loadBabylonTexture();
  68102. }
  68103. else {
  68104. this.loadHDRTexture();
  68105. }
  68106. };
  68107. HDRCubeTexture.prototype.clone = function () {
  68108. var scene = this.getScene();
  68109. if (!scene) {
  68110. return this;
  68111. }
  68112. var size = (this._isBABYLONPreprocessed ? null : this._size);
  68113. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  68114. // Base texture
  68115. newTexture.level = this.level;
  68116. newTexture.wrapU = this.wrapU;
  68117. newTexture.wrapV = this.wrapV;
  68118. newTexture.coordinatesIndex = this.coordinatesIndex;
  68119. newTexture.coordinatesMode = this.coordinatesMode;
  68120. return newTexture;
  68121. };
  68122. // Methods
  68123. HDRCubeTexture.prototype.delayLoad = function () {
  68124. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  68125. return;
  68126. }
  68127. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  68128. this._texture = this._getFromCache(this.url, this._noMipmap);
  68129. if (!this._texture) {
  68130. this.loadTexture();
  68131. }
  68132. };
  68133. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  68134. return this._textureMatrix;
  68135. };
  68136. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  68137. this._textureMatrix = value;
  68138. };
  68139. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  68140. var texture = null;
  68141. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  68142. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  68143. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  68144. texture.name = parsedTexture.name;
  68145. texture.hasAlpha = parsedTexture.hasAlpha;
  68146. texture.level = parsedTexture.level;
  68147. texture.coordinatesMode = parsedTexture.coordinatesMode;
  68148. texture.isBlocking = parsedTexture.isBlocking;
  68149. }
  68150. return texture;
  68151. };
  68152. HDRCubeTexture.prototype.serialize = function () {
  68153. if (!this.name) {
  68154. return null;
  68155. }
  68156. var serializationObject = {};
  68157. serializationObject.name = this.name;
  68158. serializationObject.hasAlpha = this.hasAlpha;
  68159. serializationObject.isCube = true;
  68160. serializationObject.level = this.level;
  68161. serializationObject.size = this._size;
  68162. serializationObject.coordinatesMode = this.coordinatesMode;
  68163. serializationObject.useInGammaSpace = this._useInGammaSpace;
  68164. serializationObject.generateHarmonics = this._generateHarmonics;
  68165. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  68166. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  68167. serializationObject.customType = "BABYLON.HDRCubeTexture";
  68168. serializationObject.noMipmap = this._noMipmap;
  68169. serializationObject.isBlocking = this._isBlocking;
  68170. return serializationObject;
  68171. };
  68172. /**
  68173. * Saves as a file the data contained in the texture in a binary format.
  68174. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68175. * as the spherical used in the lighting.
  68176. * @param url The HDR file url.
  68177. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68178. * @param onError Method called if any error happens during download.
  68179. * @return The packed binary data.
  68180. */
  68181. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  68182. if (onError === void 0) { onError = null; }
  68183. var callback = function (buffer) {
  68184. var data = new Blob([buffer], { type: 'application/octet-stream' });
  68185. // Returns a URL you can use as a href.
  68186. var objUrl = window.URL.createObjectURL(data);
  68187. // Simulates a link to it and click to dowload.
  68188. var a = document.createElement("a");
  68189. document.body.appendChild(a);
  68190. a.style.display = "none";
  68191. a.href = objUrl;
  68192. a.download = "envmap.babylon.hdr";
  68193. a.click();
  68194. };
  68195. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  68196. };
  68197. /**
  68198. * Serializes the data contained in the texture in a binary format.
  68199. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68200. * as the spherical used in the lighting.
  68201. * @param url The HDR file url.
  68202. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68203. * @param onError Method called if any error happens during download.
  68204. * @return The packed binary data.
  68205. */
  68206. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  68207. if (onError === void 0) { onError = null; }
  68208. // Needs the url tho create the texture.
  68209. if (!url) {
  68210. return;
  68211. }
  68212. // Check Power of two size.
  68213. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  68214. return;
  68215. }
  68216. // Coming Back in 3.x.
  68217. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  68218. };
  68219. HDRCubeTexture._facesMapping = [
  68220. "right",
  68221. "left",
  68222. "up",
  68223. "down",
  68224. "front",
  68225. "back"
  68226. ];
  68227. return HDRCubeTexture;
  68228. }(BABYLON.BaseTexture));
  68229. BABYLON.HDRCubeTexture = HDRCubeTexture;
  68230. })(BABYLON || (BABYLON = {}));
  68231. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  68232. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  68233. // Huge respect for a such great lib.
  68234. // Earcut license:
  68235. // Copyright (c) 2016, Mapbox
  68236. //
  68237. // Permission to use, copy, modify, and/or distribute this software for any purpose
  68238. // with or without fee is hereby granted, provided that the above copyright notice
  68239. // and this permission notice appear in all copies.
  68240. //
  68241. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  68242. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  68243. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  68244. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  68245. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  68246. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  68247. // THIS SOFTWARE.
  68248. var Earcut;
  68249. (function (Earcut) {
  68250. /**
  68251. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  68252. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  68253. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  68254. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  68255. */
  68256. function earcut(data, holeIndices, dim) {
  68257. dim = dim || 2;
  68258. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  68259. if (!outerNode)
  68260. return triangles;
  68261. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  68262. if (hasHoles)
  68263. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  68264. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  68265. if (data.length > 80 * dim) {
  68266. minX = maxX = data[0];
  68267. minY = maxY = data[1];
  68268. for (var i = dim; i < outerLen; i += dim) {
  68269. x = data[i];
  68270. y = data[i + 1];
  68271. if (x < minX)
  68272. minX = x;
  68273. if (y < minY)
  68274. minY = y;
  68275. if (x > maxX)
  68276. maxX = x;
  68277. if (y > maxY)
  68278. maxY = y;
  68279. }
  68280. // minX, minY and size are later used to transform coords into integers for z-order calculation
  68281. size = Math.max(maxX - minX, maxY - minY);
  68282. }
  68283. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  68284. return triangles;
  68285. }
  68286. Earcut.earcut = earcut;
  68287. var Node = /** @class */ (function () {
  68288. function Node(i, x, y) {
  68289. this.i = i;
  68290. this.x = x;
  68291. this.y = y;
  68292. this.prev = null;
  68293. this.next = null;
  68294. this.z = null;
  68295. this.prevZ = null;
  68296. this.nextZ = null;
  68297. this.steiner = false;
  68298. }
  68299. return Node;
  68300. }());
  68301. // create a circular doubly linked list from polygon points in the specified winding order
  68302. function linkedList(data, start, end, dim, clockwise) {
  68303. var i, last = null;
  68304. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  68305. for (i = start; i < end; i += dim)
  68306. last = insertNode(i, data[i], data[i + 1], last);
  68307. }
  68308. else {
  68309. for (i = end - dim; i >= start; i -= dim)
  68310. last = insertNode(i, data[i], data[i + 1], last);
  68311. }
  68312. if (last && equals(last, last.next)) {
  68313. removeNode(last);
  68314. last = last.next;
  68315. }
  68316. return last;
  68317. }
  68318. // eliminate colinear or duplicate points
  68319. function filterPoints(start, end) {
  68320. if (!start)
  68321. return start;
  68322. if (!end)
  68323. end = start;
  68324. var p = start, again;
  68325. do {
  68326. again = false;
  68327. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  68328. removeNode(p);
  68329. p = end = p.prev;
  68330. if (p === p.next)
  68331. return undefined;
  68332. again = true;
  68333. }
  68334. else {
  68335. p = p.next;
  68336. }
  68337. } while (again || p !== end);
  68338. return end;
  68339. }
  68340. // main ear slicing loop which triangulates a polygon (given as a linked list)
  68341. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  68342. if (!ear)
  68343. return;
  68344. // interlink polygon nodes in z-order
  68345. if (!pass && size)
  68346. indexCurve(ear, minX, minY, size);
  68347. var stop = ear, prev, next;
  68348. // iterate through ears, slicing them one by one
  68349. while (ear.prev !== ear.next) {
  68350. prev = ear.prev;
  68351. next = ear.next;
  68352. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  68353. // cut off the triangle
  68354. triangles.push(prev.i / dim);
  68355. triangles.push(ear.i / dim);
  68356. triangles.push(next.i / dim);
  68357. removeNode(ear);
  68358. // skipping the next vertice leads to less sliver triangles
  68359. ear = next.next;
  68360. stop = next.next;
  68361. continue;
  68362. }
  68363. ear = next;
  68364. // if we looped through the whole remaining polygon and can't find any more ears
  68365. if (ear === stop) {
  68366. // try filtering points and slicing again
  68367. if (!pass) {
  68368. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  68369. // if this didn't work, try curing all small self-intersections locally
  68370. }
  68371. else if (pass === 1) {
  68372. ear = cureLocalIntersections(ear, triangles, dim);
  68373. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  68374. // as a last resort, try splitting the remaining polygon into two
  68375. }
  68376. else if (pass === 2) {
  68377. splitEarcut(ear, triangles, dim, minX, minY, size);
  68378. }
  68379. break;
  68380. }
  68381. }
  68382. }
  68383. // check whether a polygon node forms a valid ear with adjacent nodes
  68384. function isEar(ear) {
  68385. var a = ear.prev, b = ear, c = ear.next;
  68386. if (area(a, b, c) >= 0)
  68387. return false; // reflex, can't be an ear
  68388. // now make sure we don't have other points inside the potential ear
  68389. var p = ear.next.next;
  68390. while (p !== ear.prev) {
  68391. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68392. area(p.prev, p, p.next) >= 0)
  68393. return false;
  68394. p = p.next;
  68395. }
  68396. return true;
  68397. }
  68398. function isEarHashed(ear, minX, minY, size) {
  68399. var a = ear.prev, b = ear, c = ear.next;
  68400. if (area(a, b, c) >= 0)
  68401. return false; // reflex, can't be an ear
  68402. // triangle bbox; min & max are calculated like this for speed
  68403. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  68404. // z-order range for the current triangle bbox;
  68405. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  68406. // first look for points inside the triangle in increasing z-order
  68407. var p = ear.nextZ;
  68408. while (p && p.z <= maxZ) {
  68409. if (p !== ear.prev &&
  68410. p !== ear.next &&
  68411. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68412. area(p.prev, p, p.next) >= 0)
  68413. return false;
  68414. p = p.nextZ;
  68415. }
  68416. // then look for points in decreasing z-order
  68417. p = ear.prevZ;
  68418. while (p && p.z >= minZ) {
  68419. if (p !== ear.prev &&
  68420. p !== ear.next &&
  68421. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68422. area(p.prev, p, p.next) >= 0)
  68423. return false;
  68424. p = p.prevZ;
  68425. }
  68426. return true;
  68427. }
  68428. // go through all polygon nodes and cure small local self-intersections
  68429. function cureLocalIntersections(start, triangles, dim) {
  68430. var p = start;
  68431. do {
  68432. var a = p.prev, b = p.next.next;
  68433. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68434. triangles.push(a.i / dim);
  68435. triangles.push(p.i / dim);
  68436. triangles.push(b.i / dim);
  68437. // remove two nodes involved
  68438. removeNode(p);
  68439. removeNode(p.next);
  68440. p = start = b;
  68441. }
  68442. p = p.next;
  68443. } while (p !== start);
  68444. return p;
  68445. }
  68446. // try splitting polygon into two and triangulate them independently
  68447. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68448. // look for a valid diagonal that divides the polygon into two
  68449. var a = start;
  68450. do {
  68451. var b = a.next.next;
  68452. while (b !== a.prev) {
  68453. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68454. // split the polygon in two by the diagonal
  68455. var c = splitPolygon(a, b);
  68456. // filter colinear points around the cuts
  68457. a = filterPoints(a, a.next);
  68458. c = filterPoints(c, c.next);
  68459. // run earcut on each half
  68460. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68461. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68462. return;
  68463. }
  68464. b = b.next;
  68465. }
  68466. a = a.next;
  68467. } while (a !== start);
  68468. }
  68469. // link every hole into the outer loop, producing a single-ring polygon without holes
  68470. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68471. var queue = [], i, len, start, end, list;
  68472. for (i = 0, len = holeIndices.length; i < len; i++) {
  68473. start = holeIndices[i] * dim;
  68474. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68475. list = linkedList(data, start, end, dim, false);
  68476. if (list === list.next)
  68477. list.steiner = true;
  68478. queue.push(getLeftmost(list));
  68479. }
  68480. queue.sort(compareX);
  68481. // process holes from left to right
  68482. for (i = 0; i < queue.length; i++) {
  68483. eliminateHole(queue[i], outerNode);
  68484. outerNode = filterPoints(outerNode, outerNode.next);
  68485. }
  68486. return outerNode;
  68487. }
  68488. function compareX(a, b) {
  68489. return a.x - b.x;
  68490. }
  68491. // find a bridge between vertices that connects hole with an outer ring and and link it
  68492. function eliminateHole(hole, outerNode) {
  68493. outerNode = findHoleBridge(hole, outerNode);
  68494. if (outerNode) {
  68495. var b = splitPolygon(outerNode, hole);
  68496. filterPoints(b, b.next);
  68497. }
  68498. }
  68499. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68500. function findHoleBridge(hole, outerNode) {
  68501. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68502. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68503. // segment's endpoint with lesser x will be potential connection point
  68504. do {
  68505. if (hy <= p.y && hy >= p.next.y) {
  68506. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68507. if (x <= hx && x > qx) {
  68508. qx = x;
  68509. if (x === hx) {
  68510. if (hy === p.y)
  68511. return p;
  68512. if (hy === p.next.y)
  68513. return p.next;
  68514. }
  68515. m = p.x < p.next.x ? p : p.next;
  68516. }
  68517. }
  68518. p = p.next;
  68519. } while (p !== outerNode);
  68520. if (!m)
  68521. return null;
  68522. if (hx === qx)
  68523. return m.prev; // hole touches outer segment; pick lower endpoint
  68524. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68525. // if there are no points found, we have a valid connection;
  68526. // otherwise choose the point of the minimum angle with the ray as connection point
  68527. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68528. p = m.next;
  68529. while (p !== stop) {
  68530. if (hx >= p.x &&
  68531. p.x >= mx &&
  68532. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68533. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68534. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68535. m = p;
  68536. tanMin = tan;
  68537. }
  68538. }
  68539. p = p.next;
  68540. }
  68541. return m;
  68542. }
  68543. // interlink polygon nodes in z-order
  68544. function indexCurve(start, minX, minY, size) {
  68545. var p = start;
  68546. do {
  68547. if (p.z === null)
  68548. p.z = zOrder(p.x, p.y, minX, minY, size);
  68549. p.prevZ = p.prev;
  68550. p.nextZ = p.next;
  68551. p = p.next;
  68552. } while (p !== start);
  68553. p.prevZ.nextZ = null;
  68554. p.prevZ = null;
  68555. sortLinked(p);
  68556. }
  68557. // Simon Tatham's linked list merge sort algorithm
  68558. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68559. function sortLinked(list) {
  68560. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68561. do {
  68562. p = list;
  68563. list = null;
  68564. tail = null;
  68565. numMerges = 0;
  68566. while (p) {
  68567. numMerges++;
  68568. q = p;
  68569. pSize = 0;
  68570. for (i = 0; i < inSize; i++) {
  68571. pSize++;
  68572. q = q.nextZ;
  68573. if (!q)
  68574. break;
  68575. }
  68576. qSize = inSize;
  68577. while (pSize > 0 || (qSize > 0 && q)) {
  68578. if (pSize === 0) {
  68579. e = q;
  68580. q = q.nextZ;
  68581. qSize--;
  68582. }
  68583. else if (qSize === 0 || !q) {
  68584. e = p;
  68585. p = p.nextZ;
  68586. pSize--;
  68587. }
  68588. else if (p.z <= q.z) {
  68589. e = p;
  68590. p = p.nextZ;
  68591. pSize--;
  68592. }
  68593. else {
  68594. e = q;
  68595. q = q.nextZ;
  68596. qSize--;
  68597. }
  68598. if (tail)
  68599. tail.nextZ = e;
  68600. else
  68601. list = e;
  68602. e.prevZ = tail;
  68603. tail = e;
  68604. }
  68605. p = q;
  68606. }
  68607. tail.nextZ = null;
  68608. inSize *= 2;
  68609. } while (numMerges > 1);
  68610. return list;
  68611. }
  68612. // z-order of a point given coords and size of the data bounding box
  68613. function zOrder(x, y, minX, minY, size) {
  68614. // coords are transformed into non-negative 15-bit integer range
  68615. x = 32767 * (x - minX) / size;
  68616. y = 32767 * (y - minY) / size;
  68617. x = (x | (x << 8)) & 0x00FF00FF;
  68618. x = (x | (x << 4)) & 0x0F0F0F0F;
  68619. x = (x | (x << 2)) & 0x33333333;
  68620. x = (x | (x << 1)) & 0x55555555;
  68621. y = (y | (y << 8)) & 0x00FF00FF;
  68622. y = (y | (y << 4)) & 0x0F0F0F0F;
  68623. y = (y | (y << 2)) & 0x33333333;
  68624. y = (y | (y << 1)) & 0x55555555;
  68625. return x | (y << 1);
  68626. }
  68627. // find the leftmost node of a polygon ring
  68628. function getLeftmost(start) {
  68629. var p = start, leftmost = start;
  68630. do {
  68631. if (p.x < leftmost.x)
  68632. leftmost = p;
  68633. p = p.next;
  68634. } while (p !== start);
  68635. return leftmost;
  68636. }
  68637. // check if a point lies within a convex triangle
  68638. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68639. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68640. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68641. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68642. }
  68643. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68644. function isValidDiagonal(a, b) {
  68645. return a.next.i !== b.i &&
  68646. a.prev.i !== b.i &&
  68647. !intersectsPolygon(a, b) &&
  68648. locallyInside(a, b) &&
  68649. locallyInside(b, a) &&
  68650. middleInside(a, b);
  68651. }
  68652. // signed area of a triangle
  68653. function area(p, q, r) {
  68654. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68655. }
  68656. // check if two points are equal
  68657. function equals(p1, p2) {
  68658. return p1.x === p2.x && p1.y === p2.y;
  68659. }
  68660. // check if two segments intersect
  68661. function intersects(p1, q1, p2, q2) {
  68662. if ((equals(p1, q1) && equals(p2, q2)) ||
  68663. (equals(p1, q2) && equals(p2, q1)))
  68664. return true;
  68665. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  68666. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  68667. }
  68668. // check if a polygon diagonal intersects any polygon segments
  68669. function intersectsPolygon(a, b) {
  68670. var p = a;
  68671. do {
  68672. if (p.i !== a.i &&
  68673. p.next.i !== a.i &&
  68674. p.i !== b.i &&
  68675. p.next.i !== b.i &&
  68676. intersects(p, p.next, a, b))
  68677. return true;
  68678. p = p.next;
  68679. } while (p !== a);
  68680. return false;
  68681. }
  68682. // check if a polygon diagonal is locally inside the polygon
  68683. function locallyInside(a, b) {
  68684. return area(a.prev, a, a.next) < 0
  68685. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  68686. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  68687. }
  68688. // check if the middle point of a polygon diagonal is inside the polygon
  68689. function middleInside(a, b) {
  68690. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  68691. do {
  68692. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  68693. inside = !inside;
  68694. p = p.next;
  68695. } while (p !== a);
  68696. return inside;
  68697. }
  68698. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  68699. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  68700. function splitPolygon(a, b) {
  68701. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  68702. a.next = b;
  68703. b.prev = a;
  68704. a2.next = an;
  68705. an.prev = a2;
  68706. b2.next = a2;
  68707. a2.prev = b2;
  68708. bp.next = b2;
  68709. b2.prev = bp;
  68710. return b2;
  68711. }
  68712. // create a node and optionally link it with previous one (in a circular doubly linked list)
  68713. function insertNode(i, x, y, last) {
  68714. var p = new Node(i, x, y);
  68715. if (!last) {
  68716. p.prev = p;
  68717. p.next = p;
  68718. }
  68719. else {
  68720. p.next = last.next;
  68721. p.prev = last;
  68722. last.next.prev = p;
  68723. last.next = p;
  68724. }
  68725. return p;
  68726. }
  68727. function removeNode(p) {
  68728. p.next.prev = p.prev;
  68729. p.prev.next = p.next;
  68730. if (p.prevZ)
  68731. p.prevZ.nextZ = p.nextZ;
  68732. if (p.nextZ)
  68733. p.nextZ.prevZ = p.prevZ;
  68734. }
  68735. /**
  68736. * return a percentage difference between the polygon area and its triangulation area;
  68737. * used to verify correctness of triangulation
  68738. */
  68739. function deviation(data, holeIndices, dim, triangles) {
  68740. var hasHoles = holeIndices && holeIndices.length;
  68741. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  68742. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  68743. if (hasHoles) {
  68744. for (var i = 0, len = holeIndices.length; i < len; i++) {
  68745. var start = holeIndices[i] * dim;
  68746. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68747. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  68748. }
  68749. }
  68750. var trianglesArea = 0;
  68751. for (i = 0; i < triangles.length; i += 3) {
  68752. var a = triangles[i] * dim;
  68753. var b = triangles[i + 1] * dim;
  68754. var c = triangles[i + 2] * dim;
  68755. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  68756. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  68757. }
  68758. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  68759. }
  68760. Earcut.deviation = deviation;
  68761. ;
  68762. function signedArea(data, start, end, dim) {
  68763. var sum = 0;
  68764. for (var i = start, j = end - dim; i < end; i += dim) {
  68765. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  68766. j = i;
  68767. }
  68768. return sum;
  68769. }
  68770. /**
  68771. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  68772. */
  68773. function flatten(data) {
  68774. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  68775. for (var i = 0; i < data.length; i++) {
  68776. for (var j = 0; j < data[i].length; j++) {
  68777. for (var d = 0; d < dim; d++)
  68778. result.vertices.push(data[i][j][d]);
  68779. }
  68780. if (i > 0) {
  68781. holeIndex += data[i - 1].length;
  68782. result.holes.push(holeIndex);
  68783. }
  68784. }
  68785. return result;
  68786. }
  68787. Earcut.flatten = flatten;
  68788. ;
  68789. })(Earcut || (Earcut = {}));
  68790. //# sourceMappingURL=babylon.earcut.js.map
  68791. var BABYLON;
  68792. (function (BABYLON) {
  68793. var IndexedVector2 = /** @class */ (function (_super) {
  68794. __extends(IndexedVector2, _super);
  68795. function IndexedVector2(original, index) {
  68796. var _this = _super.call(this, original.x, original.y) || this;
  68797. _this.index = index;
  68798. return _this;
  68799. }
  68800. return IndexedVector2;
  68801. }(BABYLON.Vector2));
  68802. var PolygonPoints = /** @class */ (function () {
  68803. function PolygonPoints() {
  68804. this.elements = new Array();
  68805. }
  68806. PolygonPoints.prototype.add = function (originalPoints) {
  68807. var _this = this;
  68808. var result = new Array();
  68809. originalPoints.forEach(function (point) {
  68810. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  68811. var newPoint = new IndexedVector2(point, _this.elements.length);
  68812. result.push(newPoint);
  68813. _this.elements.push(newPoint);
  68814. }
  68815. });
  68816. return result;
  68817. };
  68818. PolygonPoints.prototype.computeBounds = function () {
  68819. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68820. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68821. this.elements.forEach(function (point) {
  68822. // x
  68823. if (point.x < lmin.x) {
  68824. lmin.x = point.x;
  68825. }
  68826. else if (point.x > lmax.x) {
  68827. lmax.x = point.x;
  68828. }
  68829. // y
  68830. if (point.y < lmin.y) {
  68831. lmin.y = point.y;
  68832. }
  68833. else if (point.y > lmax.y) {
  68834. lmax.y = point.y;
  68835. }
  68836. });
  68837. return {
  68838. min: lmin,
  68839. max: lmax,
  68840. width: lmax.x - lmin.x,
  68841. height: lmax.y - lmin.y
  68842. };
  68843. };
  68844. return PolygonPoints;
  68845. }());
  68846. var Polygon = /** @class */ (function () {
  68847. function Polygon() {
  68848. }
  68849. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  68850. return [
  68851. new BABYLON.Vector2(xmin, ymin),
  68852. new BABYLON.Vector2(xmax, ymin),
  68853. new BABYLON.Vector2(xmax, ymax),
  68854. new BABYLON.Vector2(xmin, ymax)
  68855. ];
  68856. };
  68857. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  68858. if (cx === void 0) { cx = 0; }
  68859. if (cy === void 0) { cy = 0; }
  68860. if (numberOfSides === void 0) { numberOfSides = 32; }
  68861. var result = new Array();
  68862. var angle = 0;
  68863. var increment = (Math.PI * 2) / numberOfSides;
  68864. for (var i = 0; i < numberOfSides; i++) {
  68865. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  68866. angle -= increment;
  68867. }
  68868. return result;
  68869. };
  68870. Polygon.Parse = function (input) {
  68871. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  68872. var i, result = [];
  68873. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  68874. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  68875. }
  68876. return result;
  68877. };
  68878. Polygon.StartingAt = function (x, y) {
  68879. return BABYLON.Path2.StartingAt(x, y);
  68880. };
  68881. return Polygon;
  68882. }());
  68883. BABYLON.Polygon = Polygon;
  68884. var PolygonMeshBuilder = /** @class */ (function () {
  68885. function PolygonMeshBuilder(name, contours, scene) {
  68886. this._points = new PolygonPoints();
  68887. this._outlinepoints = new PolygonPoints();
  68888. this._holes = new Array();
  68889. this._epoints = new Array();
  68890. this._eholes = new Array();
  68891. this._name = name;
  68892. this._scene = scene;
  68893. var points;
  68894. if (contours instanceof BABYLON.Path2) {
  68895. points = contours.getPoints();
  68896. }
  68897. else {
  68898. points = contours;
  68899. }
  68900. this._addToepoint(points);
  68901. this._points.add(points);
  68902. this._outlinepoints.add(points);
  68903. }
  68904. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  68905. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  68906. var p = points_1[_i];
  68907. this._epoints.push(p.x, p.y);
  68908. }
  68909. };
  68910. PolygonMeshBuilder.prototype.addHole = function (hole) {
  68911. this._points.add(hole);
  68912. var holepoints = new PolygonPoints();
  68913. holepoints.add(hole);
  68914. this._holes.push(holepoints);
  68915. this._eholes.push(this._epoints.length / 2);
  68916. this._addToepoint(hole);
  68917. return this;
  68918. };
  68919. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  68920. var _this = this;
  68921. if (updatable === void 0) { updatable = false; }
  68922. if (depth === void 0) { depth = 0; }
  68923. var result = new BABYLON.Mesh(this._name, this._scene);
  68924. var normals = new Array();
  68925. var positions = new Array();
  68926. var uvs = new Array();
  68927. var bounds = this._points.computeBounds();
  68928. this._points.elements.forEach(function (p) {
  68929. normals.push(0, 1.0, 0);
  68930. positions.push(p.x, 0, p.y);
  68931. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  68932. });
  68933. var indices = new Array();
  68934. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  68935. for (var i = 0; i < res.length; i++) {
  68936. indices.push(res[i]);
  68937. }
  68938. if (depth > 0) {
  68939. var positionscount = (positions.length / 3); //get the current pointcount
  68940. this._points.elements.forEach(function (p) {
  68941. normals.push(0, -1.0, 0);
  68942. positions.push(p.x, -depth, p.y);
  68943. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  68944. });
  68945. var totalCount = indices.length;
  68946. for (var i = 0; i < totalCount; i += 3) {
  68947. var i0 = indices[i + 0];
  68948. var i1 = indices[i + 1];
  68949. var i2 = indices[i + 2];
  68950. indices.push(i2 + positionscount);
  68951. indices.push(i1 + positionscount);
  68952. indices.push(i0 + positionscount);
  68953. }
  68954. //Add the sides
  68955. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  68956. this._holes.forEach(function (hole) {
  68957. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  68958. });
  68959. }
  68960. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  68961. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  68962. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  68963. result.setIndices(indices);
  68964. return result;
  68965. };
  68966. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  68967. var StartIndex = positions.length / 3;
  68968. var ulength = 0;
  68969. for (var i = 0; i < points.elements.length; i++) {
  68970. var p = points.elements[i];
  68971. var p1;
  68972. if ((i + 1) > points.elements.length - 1) {
  68973. p1 = points.elements[0];
  68974. }
  68975. else {
  68976. p1 = points.elements[i + 1];
  68977. }
  68978. positions.push(p.x, 0, p.y);
  68979. positions.push(p.x, -depth, p.y);
  68980. positions.push(p1.x, 0, p1.y);
  68981. positions.push(p1.x, -depth, p1.y);
  68982. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  68983. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  68984. var v3 = v2.subtract(v1);
  68985. var v4 = new BABYLON.Vector3(0, 1, 0);
  68986. var vn = BABYLON.Vector3.Cross(v3, v4);
  68987. vn = vn.normalize();
  68988. uvs.push(ulength / bounds.width, 0);
  68989. uvs.push(ulength / bounds.width, 1);
  68990. ulength += v3.length();
  68991. uvs.push((ulength / bounds.width), 0);
  68992. uvs.push((ulength / bounds.width), 1);
  68993. if (!flip) {
  68994. normals.push(-vn.x, -vn.y, -vn.z);
  68995. normals.push(-vn.x, -vn.y, -vn.z);
  68996. normals.push(-vn.x, -vn.y, -vn.z);
  68997. normals.push(-vn.x, -vn.y, -vn.z);
  68998. indices.push(StartIndex);
  68999. indices.push(StartIndex + 1);
  69000. indices.push(StartIndex + 2);
  69001. indices.push(StartIndex + 1);
  69002. indices.push(StartIndex + 3);
  69003. indices.push(StartIndex + 2);
  69004. }
  69005. else {
  69006. normals.push(vn.x, vn.y, vn.z);
  69007. normals.push(vn.x, vn.y, vn.z);
  69008. normals.push(vn.x, vn.y, vn.z);
  69009. normals.push(vn.x, vn.y, vn.z);
  69010. indices.push(StartIndex);
  69011. indices.push(StartIndex + 2);
  69012. indices.push(StartIndex + 1);
  69013. indices.push(StartIndex + 1);
  69014. indices.push(StartIndex + 2);
  69015. indices.push(StartIndex + 3);
  69016. }
  69017. StartIndex += 4;
  69018. }
  69019. ;
  69020. };
  69021. return PolygonMeshBuilder;
  69022. }());
  69023. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  69024. })(BABYLON || (BABYLON = {}));
  69025. //# sourceMappingURL=babylon.polygonMesh.js.map
  69026. var BABYLON;
  69027. (function (BABYLON) {
  69028. // Unique ID when we import meshes from Babylon to CSG
  69029. var currentCSGMeshId = 0;
  69030. // # class Vertex
  69031. // Represents a vertex of a polygon. Use your own vertex class instead of this
  69032. // one to provide additional features like texture coordinates and vertex
  69033. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  69034. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  69035. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  69036. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  69037. // is not used anywhere else.
  69038. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  69039. var Vertex = /** @class */ (function () {
  69040. function Vertex(pos, normal, uv) {
  69041. this.pos = pos;
  69042. this.normal = normal;
  69043. this.uv = uv;
  69044. }
  69045. Vertex.prototype.clone = function () {
  69046. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  69047. };
  69048. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  69049. // orientation of a polygon is flipped.
  69050. Vertex.prototype.flip = function () {
  69051. this.normal = this.normal.scale(-1);
  69052. };
  69053. // Create a new vertex between this vertex and `other` by linearly
  69054. // interpolating all properties using a parameter of `t`. Subclasses should
  69055. // override this to interpolate additional properties.
  69056. Vertex.prototype.interpolate = function (other, t) {
  69057. 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));
  69058. };
  69059. return Vertex;
  69060. }());
  69061. // # class Plane
  69062. // Represents a plane in 3D space.
  69063. var Plane = /** @class */ (function () {
  69064. function Plane(normal, w) {
  69065. this.normal = normal;
  69066. this.w = w;
  69067. }
  69068. Plane.FromPoints = function (a, b, c) {
  69069. var v0 = c.subtract(a);
  69070. var v1 = b.subtract(a);
  69071. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  69072. return null;
  69073. }
  69074. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  69075. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  69076. };
  69077. Plane.prototype.clone = function () {
  69078. return new Plane(this.normal.clone(), this.w);
  69079. };
  69080. Plane.prototype.flip = function () {
  69081. this.normal.scaleInPlace(-1);
  69082. this.w = -this.w;
  69083. };
  69084. // Split `polygon` by this plane if needed, then put the polygon or polygon
  69085. // fragments in the appropriate lists. Coplanar polygons go into either
  69086. // `coplanarFront` or `coplanarBack` depending on their orientation with
  69087. // respect to this plane. Polygons in front or in back of this plane go into
  69088. // either `front` or `back`.
  69089. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  69090. var COPLANAR = 0;
  69091. var FRONT = 1;
  69092. var BACK = 2;
  69093. var SPANNING = 3;
  69094. // Classify each point as well as the entire polygon into one of the above
  69095. // four classes.
  69096. var polygonType = 0;
  69097. var types = [];
  69098. var i;
  69099. var t;
  69100. for (i = 0; i < polygon.vertices.length; i++) {
  69101. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  69102. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  69103. polygonType |= type;
  69104. types.push(type);
  69105. }
  69106. // Put the polygon in the correct list, splitting it when necessary.
  69107. switch (polygonType) {
  69108. case COPLANAR:
  69109. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  69110. break;
  69111. case FRONT:
  69112. front.push(polygon);
  69113. break;
  69114. case BACK:
  69115. back.push(polygon);
  69116. break;
  69117. case SPANNING:
  69118. var f = [], b = [];
  69119. for (i = 0; i < polygon.vertices.length; i++) {
  69120. var j = (i + 1) % polygon.vertices.length;
  69121. var ti = types[i], tj = types[j];
  69122. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  69123. if (ti !== BACK)
  69124. f.push(vi);
  69125. if (ti !== FRONT)
  69126. b.push(ti !== BACK ? vi.clone() : vi);
  69127. if ((ti | tj) === SPANNING) {
  69128. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  69129. var v = vi.interpolate(vj, t);
  69130. f.push(v);
  69131. b.push(v.clone());
  69132. }
  69133. }
  69134. var poly;
  69135. if (f.length >= 3) {
  69136. poly = new Polygon(f, polygon.shared);
  69137. if (poly.plane)
  69138. front.push(poly);
  69139. }
  69140. if (b.length >= 3) {
  69141. poly = new Polygon(b, polygon.shared);
  69142. if (poly.plane)
  69143. back.push(poly);
  69144. }
  69145. break;
  69146. }
  69147. };
  69148. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  69149. // point is on the plane.
  69150. Plane.EPSILON = 1e-5;
  69151. return Plane;
  69152. }());
  69153. // # class Polygon
  69154. // Represents a convex polygon. The vertices used to initialize a polygon must
  69155. // be coplanar and form a convex loop.
  69156. //
  69157. // Each convex polygon has a `shared` property, which is shared between all
  69158. // polygons that are clones of each other or were split from the same polygon.
  69159. // This can be used to define per-polygon properties (such as surface color).
  69160. var Polygon = /** @class */ (function () {
  69161. function Polygon(vertices, shared) {
  69162. this.vertices = vertices;
  69163. this.shared = shared;
  69164. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  69165. }
  69166. Polygon.prototype.clone = function () {
  69167. var vertices = this.vertices.map(function (v) { return v.clone(); });
  69168. return new Polygon(vertices, this.shared);
  69169. };
  69170. Polygon.prototype.flip = function () {
  69171. this.vertices.reverse().map(function (v) { v.flip(); });
  69172. this.plane.flip();
  69173. };
  69174. return Polygon;
  69175. }());
  69176. // # class Node
  69177. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  69178. // by picking a polygon to split along. That polygon (and all other coplanar
  69179. // polygons) are added directly to that node and the other polygons are added to
  69180. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  69181. // no distinction between internal and leaf nodes.
  69182. var Node = /** @class */ (function () {
  69183. function Node(polygons) {
  69184. this.plane = null;
  69185. this.front = null;
  69186. this.back = null;
  69187. this.polygons = new Array();
  69188. if (polygons) {
  69189. this.build(polygons);
  69190. }
  69191. }
  69192. Node.prototype.clone = function () {
  69193. var node = new Node();
  69194. node.plane = this.plane && this.plane.clone();
  69195. node.front = this.front && this.front.clone();
  69196. node.back = this.back && this.back.clone();
  69197. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  69198. return node;
  69199. };
  69200. // Convert solid space to empty space and empty space to solid space.
  69201. Node.prototype.invert = function () {
  69202. for (var i = 0; i < this.polygons.length; i++) {
  69203. this.polygons[i].flip();
  69204. }
  69205. if (this.plane) {
  69206. this.plane.flip();
  69207. }
  69208. if (this.front) {
  69209. this.front.invert();
  69210. }
  69211. if (this.back) {
  69212. this.back.invert();
  69213. }
  69214. var temp = this.front;
  69215. this.front = this.back;
  69216. this.back = temp;
  69217. };
  69218. // Recursively remove all polygons in `polygons` that are inside this BSP
  69219. // tree.
  69220. Node.prototype.clipPolygons = function (polygons) {
  69221. if (!this.plane)
  69222. return polygons.slice();
  69223. var front = new Array(), back = new Array();
  69224. for (var i = 0; i < polygons.length; i++) {
  69225. this.plane.splitPolygon(polygons[i], front, back, front, back);
  69226. }
  69227. if (this.front) {
  69228. front = this.front.clipPolygons(front);
  69229. }
  69230. if (this.back) {
  69231. back = this.back.clipPolygons(back);
  69232. }
  69233. else {
  69234. back = [];
  69235. }
  69236. return front.concat(back);
  69237. };
  69238. // Remove all polygons in this BSP tree that are inside the other BSP tree
  69239. // `bsp`.
  69240. Node.prototype.clipTo = function (bsp) {
  69241. this.polygons = bsp.clipPolygons(this.polygons);
  69242. if (this.front)
  69243. this.front.clipTo(bsp);
  69244. if (this.back)
  69245. this.back.clipTo(bsp);
  69246. };
  69247. // Return a list of all polygons in this BSP tree.
  69248. Node.prototype.allPolygons = function () {
  69249. var polygons = this.polygons.slice();
  69250. if (this.front)
  69251. polygons = polygons.concat(this.front.allPolygons());
  69252. if (this.back)
  69253. polygons = polygons.concat(this.back.allPolygons());
  69254. return polygons;
  69255. };
  69256. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  69257. // new polygons are filtered down to the bottom of the tree and become new
  69258. // nodes there. Each set of polygons is partitioned using the first polygon
  69259. // (no heuristic is used to pick a good split).
  69260. Node.prototype.build = function (polygons) {
  69261. if (!polygons.length)
  69262. return;
  69263. if (!this.plane)
  69264. this.plane = polygons[0].plane.clone();
  69265. var front = new Array(), back = new Array();
  69266. for (var i = 0; i < polygons.length; i++) {
  69267. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  69268. }
  69269. if (front.length) {
  69270. if (!this.front)
  69271. this.front = new Node();
  69272. this.front.build(front);
  69273. }
  69274. if (back.length) {
  69275. if (!this.back)
  69276. this.back = new Node();
  69277. this.back.build(back);
  69278. }
  69279. };
  69280. return Node;
  69281. }());
  69282. var CSG = /** @class */ (function () {
  69283. function CSG() {
  69284. this.polygons = new Array();
  69285. }
  69286. // Convert BABYLON.Mesh to BABYLON.CSG
  69287. CSG.FromMesh = function (mesh) {
  69288. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  69289. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  69290. if (mesh instanceof BABYLON.Mesh) {
  69291. mesh.computeWorldMatrix(true);
  69292. matrix = mesh.getWorldMatrix();
  69293. meshPosition = mesh.position.clone();
  69294. meshRotation = mesh.rotation.clone();
  69295. if (mesh.rotationQuaternion) {
  69296. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  69297. }
  69298. meshScaling = mesh.scaling.clone();
  69299. }
  69300. else {
  69301. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  69302. }
  69303. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69304. var subMeshes = mesh.subMeshes;
  69305. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  69306. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  69307. vertices = [];
  69308. for (var j = 0; j < 3; j++) {
  69309. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  69310. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  69311. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  69312. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  69313. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  69314. vertex = new Vertex(position, normal, uv);
  69315. vertices.push(vertex);
  69316. }
  69317. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  69318. // To handle the case of degenerated triangle
  69319. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  69320. if (polygon.plane)
  69321. polygons.push(polygon);
  69322. }
  69323. }
  69324. var csg = CSG.FromPolygons(polygons);
  69325. csg.matrix = matrix;
  69326. csg.position = meshPosition;
  69327. csg.rotation = meshRotation;
  69328. csg.scaling = meshScaling;
  69329. csg.rotationQuaternion = meshRotationQuaternion;
  69330. currentCSGMeshId++;
  69331. return csg;
  69332. };
  69333. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  69334. CSG.FromPolygons = function (polygons) {
  69335. var csg = new CSG();
  69336. csg.polygons = polygons;
  69337. return csg;
  69338. };
  69339. CSG.prototype.clone = function () {
  69340. var csg = new CSG();
  69341. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  69342. csg.copyTransformAttributes(this);
  69343. return csg;
  69344. };
  69345. CSG.prototype.union = function (csg) {
  69346. var a = new Node(this.clone().polygons);
  69347. var b = new Node(csg.clone().polygons);
  69348. a.clipTo(b);
  69349. b.clipTo(a);
  69350. b.invert();
  69351. b.clipTo(a);
  69352. b.invert();
  69353. a.build(b.allPolygons());
  69354. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69355. };
  69356. CSG.prototype.unionInPlace = function (csg) {
  69357. var a = new Node(this.polygons);
  69358. var b = new Node(csg.polygons);
  69359. a.clipTo(b);
  69360. b.clipTo(a);
  69361. b.invert();
  69362. b.clipTo(a);
  69363. b.invert();
  69364. a.build(b.allPolygons());
  69365. this.polygons = a.allPolygons();
  69366. };
  69367. CSG.prototype.subtract = function (csg) {
  69368. var a = new Node(this.clone().polygons);
  69369. var b = new Node(csg.clone().polygons);
  69370. a.invert();
  69371. a.clipTo(b);
  69372. b.clipTo(a);
  69373. b.invert();
  69374. b.clipTo(a);
  69375. b.invert();
  69376. a.build(b.allPolygons());
  69377. a.invert();
  69378. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69379. };
  69380. CSG.prototype.subtractInPlace = function (csg) {
  69381. var a = new Node(this.polygons);
  69382. var b = new Node(csg.polygons);
  69383. a.invert();
  69384. a.clipTo(b);
  69385. b.clipTo(a);
  69386. b.invert();
  69387. b.clipTo(a);
  69388. b.invert();
  69389. a.build(b.allPolygons());
  69390. a.invert();
  69391. this.polygons = a.allPolygons();
  69392. };
  69393. CSG.prototype.intersect = function (csg) {
  69394. var a = new Node(this.clone().polygons);
  69395. var b = new Node(csg.clone().polygons);
  69396. a.invert();
  69397. b.clipTo(a);
  69398. b.invert();
  69399. a.clipTo(b);
  69400. b.clipTo(a);
  69401. a.build(b.allPolygons());
  69402. a.invert();
  69403. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69404. };
  69405. CSG.prototype.intersectInPlace = function (csg) {
  69406. var a = new Node(this.polygons);
  69407. var b = new Node(csg.polygons);
  69408. a.invert();
  69409. b.clipTo(a);
  69410. b.invert();
  69411. a.clipTo(b);
  69412. b.clipTo(a);
  69413. a.build(b.allPolygons());
  69414. a.invert();
  69415. this.polygons = a.allPolygons();
  69416. };
  69417. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  69418. // not modified.
  69419. CSG.prototype.inverse = function () {
  69420. var csg = this.clone();
  69421. csg.inverseInPlace();
  69422. return csg;
  69423. };
  69424. CSG.prototype.inverseInPlace = function () {
  69425. this.polygons.map(function (p) { p.flip(); });
  69426. };
  69427. // This is used to keep meshes transformations so they can be restored
  69428. // when we build back a Babylon Mesh
  69429. // NB : All CSG operations are performed in world coordinates
  69430. CSG.prototype.copyTransformAttributes = function (csg) {
  69431. this.matrix = csg.matrix;
  69432. this.position = csg.position;
  69433. this.rotation = csg.rotation;
  69434. this.scaling = csg.scaling;
  69435. this.rotationQuaternion = csg.rotationQuaternion;
  69436. return this;
  69437. };
  69438. // Build Raw mesh from CSG
  69439. // Coordinates here are in world space
  69440. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69441. var matrix = this.matrix.clone();
  69442. matrix.invert();
  69443. 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;
  69444. if (keepSubMeshes) {
  69445. // Sort Polygons, since subMeshes are indices range
  69446. polygons.sort(function (a, b) {
  69447. if (a.shared.meshId === b.shared.meshId) {
  69448. return a.shared.subMeshId - b.shared.subMeshId;
  69449. }
  69450. else {
  69451. return a.shared.meshId - b.shared.meshId;
  69452. }
  69453. });
  69454. }
  69455. for (var i = 0, il = polygons.length; i < il; i++) {
  69456. polygon = polygons[i];
  69457. // Building SubMeshes
  69458. if (!subMesh_dict[polygon.shared.meshId]) {
  69459. subMesh_dict[polygon.shared.meshId] = {};
  69460. }
  69461. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69462. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69463. indexStart: +Infinity,
  69464. indexEnd: -Infinity,
  69465. materialIndex: polygon.shared.materialIndex
  69466. };
  69467. }
  69468. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69469. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69470. polygonIndices[0] = 0;
  69471. polygonIndices[1] = j - 1;
  69472. polygonIndices[2] = j;
  69473. for (var k = 0; k < 3; k++) {
  69474. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69475. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69476. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69477. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69478. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69479. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69480. // Check if 2 points can be merged
  69481. if (!(typeof vertex_idx !== 'undefined' &&
  69482. normals[vertex_idx * 3] === localNormal.x &&
  69483. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69484. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69485. uvs[vertex_idx * 2] === uv.x &&
  69486. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69487. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69488. uvs.push(uv.x, uv.y);
  69489. normals.push(normal.x, normal.y, normal.z);
  69490. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69491. }
  69492. indices.push(vertex_idx);
  69493. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69494. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69495. currentIndex++;
  69496. }
  69497. }
  69498. }
  69499. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69500. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69501. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69502. mesh.setIndices(indices, null);
  69503. if (keepSubMeshes) {
  69504. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69505. var materialIndexOffset = 0, materialMaxIndex;
  69506. mesh.subMeshes = new Array();
  69507. for (var m in subMesh_dict) {
  69508. materialMaxIndex = -1;
  69509. for (var sm in subMesh_dict[m]) {
  69510. subMesh_obj = subMesh_dict[m][sm];
  69511. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69512. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69513. }
  69514. materialIndexOffset += ++materialMaxIndex;
  69515. }
  69516. }
  69517. return mesh;
  69518. };
  69519. // Build Mesh from CSG taking material and transforms into account
  69520. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69521. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69522. mesh.material = material;
  69523. mesh.position.copyFrom(this.position);
  69524. mesh.rotation.copyFrom(this.rotation);
  69525. if (this.rotationQuaternion) {
  69526. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69527. }
  69528. mesh.scaling.copyFrom(this.scaling);
  69529. mesh.computeWorldMatrix(true);
  69530. return mesh;
  69531. };
  69532. return CSG;
  69533. }());
  69534. BABYLON.CSG = CSG;
  69535. })(BABYLON || (BABYLON = {}));
  69536. //# sourceMappingURL=babylon.csg.js.map
  69537. var BABYLON;
  69538. (function (BABYLON) {
  69539. var LensFlare = /** @class */ (function () {
  69540. function LensFlare(size, position, color, imgUrl, system) {
  69541. this.size = size;
  69542. this.position = position;
  69543. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69544. this.color = color || new BABYLON.Color3(1, 1, 1);
  69545. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69546. this._system = system;
  69547. system.lensFlares.push(this);
  69548. }
  69549. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69550. return new LensFlare(size, position, color, imgUrl, system);
  69551. };
  69552. LensFlare.prototype.dispose = function () {
  69553. if (this.texture) {
  69554. this.texture.dispose();
  69555. }
  69556. // Remove from scene
  69557. var index = this._system.lensFlares.indexOf(this);
  69558. this._system.lensFlares.splice(index, 1);
  69559. };
  69560. ;
  69561. return LensFlare;
  69562. }());
  69563. BABYLON.LensFlare = LensFlare;
  69564. })(BABYLON || (BABYLON = {}));
  69565. //# sourceMappingURL=babylon.lensFlare.js.map
  69566. var BABYLON;
  69567. (function (BABYLON) {
  69568. var LensFlareSystem = /** @class */ (function () {
  69569. function LensFlareSystem(name, emitter, scene) {
  69570. this.name = name;
  69571. this.lensFlares = new Array();
  69572. this.borderLimit = 300;
  69573. this.viewportBorder = 0;
  69574. this.layerMask = 0x0FFFFFFF;
  69575. this._vertexBuffers = {};
  69576. this._isEnabled = true;
  69577. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69578. this._emitter = emitter;
  69579. this.id = name;
  69580. scene.lensFlareSystems.push(this);
  69581. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69582. var engine = scene.getEngine();
  69583. // VBO
  69584. var vertices = [];
  69585. vertices.push(1, 1);
  69586. vertices.push(-1, 1);
  69587. vertices.push(-1, -1);
  69588. vertices.push(1, -1);
  69589. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69590. // Indices
  69591. var indices = [];
  69592. indices.push(0);
  69593. indices.push(1);
  69594. indices.push(2);
  69595. indices.push(0);
  69596. indices.push(2);
  69597. indices.push(3);
  69598. this._indexBuffer = engine.createIndexBuffer(indices);
  69599. // Effects
  69600. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69601. }
  69602. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69603. get: function () {
  69604. return this._isEnabled;
  69605. },
  69606. set: function (value) {
  69607. this._isEnabled = value;
  69608. },
  69609. enumerable: true,
  69610. configurable: true
  69611. });
  69612. LensFlareSystem.prototype.getScene = function () {
  69613. return this._scene;
  69614. };
  69615. LensFlareSystem.prototype.getEmitter = function () {
  69616. return this._emitter;
  69617. };
  69618. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69619. this._emitter = newEmitter;
  69620. };
  69621. LensFlareSystem.prototype.getEmitterPosition = function () {
  69622. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69623. };
  69624. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69625. var position = this.getEmitterPosition();
  69626. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69627. this._positionX = position.x;
  69628. this._positionY = position.y;
  69629. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69630. if (this.viewportBorder > 0) {
  69631. globalViewport.x -= this.viewportBorder;
  69632. globalViewport.y -= this.viewportBorder;
  69633. globalViewport.width += this.viewportBorder * 2;
  69634. globalViewport.height += this.viewportBorder * 2;
  69635. position.x += this.viewportBorder;
  69636. position.y += this.viewportBorder;
  69637. this._positionX += this.viewportBorder;
  69638. this._positionY += this.viewportBorder;
  69639. }
  69640. if (position.z > 0) {
  69641. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69642. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69643. return true;
  69644. }
  69645. return true;
  69646. }
  69647. return false;
  69648. };
  69649. LensFlareSystem.prototype._isVisible = function () {
  69650. if (!this._isEnabled || !this._scene.activeCamera) {
  69651. return false;
  69652. }
  69653. var emitterPosition = this.getEmitterPosition();
  69654. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69655. var distance = direction.length();
  69656. direction.normalize();
  69657. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69658. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69659. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69660. };
  69661. LensFlareSystem.prototype.render = function () {
  69662. if (!this._effect.isReady() || !this._scene.activeCamera)
  69663. return false;
  69664. var engine = this._scene.getEngine();
  69665. var viewport = this._scene.activeCamera.viewport;
  69666. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  69667. // Position
  69668. if (!this.computeEffectivePosition(globalViewport)) {
  69669. return false;
  69670. }
  69671. // Visibility
  69672. if (!this._isVisible()) {
  69673. return false;
  69674. }
  69675. // Intensity
  69676. var awayX;
  69677. var awayY;
  69678. if (this._positionX < this.borderLimit + globalViewport.x) {
  69679. awayX = this.borderLimit + globalViewport.x - this._positionX;
  69680. }
  69681. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  69682. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  69683. }
  69684. else {
  69685. awayX = 0;
  69686. }
  69687. if (this._positionY < this.borderLimit + globalViewport.y) {
  69688. awayY = this.borderLimit + globalViewport.y - this._positionY;
  69689. }
  69690. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  69691. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  69692. }
  69693. else {
  69694. awayY = 0;
  69695. }
  69696. var away = (awayX > awayY) ? awayX : awayY;
  69697. away -= this.viewportBorder;
  69698. if (away > this.borderLimit) {
  69699. away = this.borderLimit;
  69700. }
  69701. var intensity = 1.0 - (away / this.borderLimit);
  69702. if (intensity < 0) {
  69703. return false;
  69704. }
  69705. if (intensity > 1.0) {
  69706. intensity = 1.0;
  69707. }
  69708. if (this.viewportBorder > 0) {
  69709. globalViewport.x += this.viewportBorder;
  69710. globalViewport.y += this.viewportBorder;
  69711. globalViewport.width -= this.viewportBorder * 2;
  69712. globalViewport.height -= this.viewportBorder * 2;
  69713. this._positionX -= this.viewportBorder;
  69714. this._positionY -= this.viewportBorder;
  69715. }
  69716. // Position
  69717. var centerX = globalViewport.x + globalViewport.width / 2;
  69718. var centerY = globalViewport.y + globalViewport.height / 2;
  69719. var distX = centerX - this._positionX;
  69720. var distY = centerY - this._positionY;
  69721. // Effects
  69722. engine.enableEffect(this._effect);
  69723. engine.setState(false);
  69724. engine.setDepthBuffer(false);
  69725. // VBOs
  69726. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69727. // Flares
  69728. for (var index = 0; index < this.lensFlares.length; index++) {
  69729. var flare = this.lensFlares[index];
  69730. engine.setAlphaMode(flare.alphaMode);
  69731. var x = centerX - (distX * flare.position);
  69732. var y = centerY - (distY * flare.position);
  69733. var cw = flare.size;
  69734. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  69735. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  69736. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  69737. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  69738. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  69739. // Texture
  69740. this._effect.setTexture("textureSampler", flare.texture);
  69741. // Color
  69742. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  69743. // Draw order
  69744. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69745. }
  69746. engine.setDepthBuffer(true);
  69747. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69748. return true;
  69749. };
  69750. LensFlareSystem.prototype.dispose = function () {
  69751. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69752. if (vertexBuffer) {
  69753. vertexBuffer.dispose();
  69754. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69755. }
  69756. if (this._indexBuffer) {
  69757. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69758. this._indexBuffer = null;
  69759. }
  69760. while (this.lensFlares.length) {
  69761. this.lensFlares[0].dispose();
  69762. }
  69763. // Remove from scene
  69764. var index = this._scene.lensFlareSystems.indexOf(this);
  69765. this._scene.lensFlareSystems.splice(index, 1);
  69766. };
  69767. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  69768. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  69769. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  69770. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  69771. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  69772. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  69773. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  69774. var parsedFlare = parsedLensFlareSystem.flares[index];
  69775. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  69776. }
  69777. return lensFlareSystem;
  69778. };
  69779. LensFlareSystem.prototype.serialize = function () {
  69780. var serializationObject = {};
  69781. serializationObject.id = this.id;
  69782. serializationObject.name = this.name;
  69783. serializationObject.emitterId = this.getEmitter().id;
  69784. serializationObject.borderLimit = this.borderLimit;
  69785. serializationObject.flares = [];
  69786. for (var index = 0; index < this.lensFlares.length; index++) {
  69787. var flare = this.lensFlares[index];
  69788. serializationObject.flares.push({
  69789. size: flare.size,
  69790. position: flare.position,
  69791. color: flare.color.asArray(),
  69792. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  69793. });
  69794. }
  69795. return serializationObject;
  69796. };
  69797. return LensFlareSystem;
  69798. }());
  69799. BABYLON.LensFlareSystem = LensFlareSystem;
  69800. })(BABYLON || (BABYLON = {}));
  69801. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  69802. var BABYLON;
  69803. (function (BABYLON) {
  69804. /**
  69805. * This is a holder class for the physics joint created by the physics plugin.
  69806. * It holds a set of functions to control the underlying joint.
  69807. */
  69808. var PhysicsJoint = /** @class */ (function () {
  69809. function PhysicsJoint(type, jointData) {
  69810. this.type = type;
  69811. this.jointData = jointData;
  69812. jointData.nativeParams = jointData.nativeParams || {};
  69813. }
  69814. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  69815. get: function () {
  69816. return this._physicsJoint;
  69817. },
  69818. set: function (newJoint) {
  69819. if (this._physicsJoint) {
  69820. //remove from the wolrd
  69821. }
  69822. this._physicsJoint = newJoint;
  69823. },
  69824. enumerable: true,
  69825. configurable: true
  69826. });
  69827. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  69828. set: function (physicsPlugin) {
  69829. this._physicsPlugin = physicsPlugin;
  69830. },
  69831. enumerable: true,
  69832. configurable: true
  69833. });
  69834. /**
  69835. * Execute a function that is physics-plugin specific.
  69836. * @param {Function} func the function that will be executed.
  69837. * It accepts two parameters: the physics world and the physics joint.
  69838. */
  69839. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  69840. func(this._physicsPlugin.world, this._physicsJoint);
  69841. };
  69842. //TODO check if the native joints are the same
  69843. //Joint Types
  69844. PhysicsJoint.DistanceJoint = 0;
  69845. PhysicsJoint.HingeJoint = 1;
  69846. PhysicsJoint.BallAndSocketJoint = 2;
  69847. PhysicsJoint.WheelJoint = 3;
  69848. PhysicsJoint.SliderJoint = 4;
  69849. //OIMO
  69850. PhysicsJoint.PrismaticJoint = 5;
  69851. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  69852. PhysicsJoint.UniversalJoint = 6;
  69853. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  69854. //Cannon
  69855. //Similar to a Ball-Joint. Different in params
  69856. PhysicsJoint.PointToPointJoint = 8;
  69857. //Cannon only at the moment
  69858. PhysicsJoint.SpringJoint = 9;
  69859. PhysicsJoint.LockJoint = 10;
  69860. return PhysicsJoint;
  69861. }());
  69862. BABYLON.PhysicsJoint = PhysicsJoint;
  69863. /**
  69864. * A class representing a physics distance joint.
  69865. */
  69866. var DistanceJoint = /** @class */ (function (_super) {
  69867. __extends(DistanceJoint, _super);
  69868. function DistanceJoint(jointData) {
  69869. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  69870. }
  69871. /**
  69872. * Update the predefined distance.
  69873. */
  69874. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  69875. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  69876. };
  69877. return DistanceJoint;
  69878. }(PhysicsJoint));
  69879. BABYLON.DistanceJoint = DistanceJoint;
  69880. var MotorEnabledJoint = /** @class */ (function (_super) {
  69881. __extends(MotorEnabledJoint, _super);
  69882. function MotorEnabledJoint(type, jointData) {
  69883. return _super.call(this, type, jointData) || this;
  69884. }
  69885. /**
  69886. * Set the motor values.
  69887. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69888. * @param {number} force the force to apply
  69889. * @param {number} maxForce max force for this motor.
  69890. */
  69891. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  69892. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69893. };
  69894. /**
  69895. * Set the motor's limits.
  69896. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69897. */
  69898. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69899. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69900. };
  69901. return MotorEnabledJoint;
  69902. }(PhysicsJoint));
  69903. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  69904. /**
  69905. * This class represents a single hinge physics joint
  69906. */
  69907. var HingeJoint = /** @class */ (function (_super) {
  69908. __extends(HingeJoint, _super);
  69909. function HingeJoint(jointData) {
  69910. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  69911. }
  69912. /**
  69913. * Set the motor values.
  69914. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69915. * @param {number} force the force to apply
  69916. * @param {number} maxForce max force for this motor.
  69917. */
  69918. HingeJoint.prototype.setMotor = function (force, maxForce) {
  69919. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69920. };
  69921. /**
  69922. * Set the motor's limits.
  69923. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69924. */
  69925. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  69926. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  69927. };
  69928. return HingeJoint;
  69929. }(MotorEnabledJoint));
  69930. BABYLON.HingeJoint = HingeJoint;
  69931. /**
  69932. * This class represents a dual hinge physics joint (same as wheel joint)
  69933. */
  69934. var Hinge2Joint = /** @class */ (function (_super) {
  69935. __extends(Hinge2Joint, _super);
  69936. function Hinge2Joint(jointData) {
  69937. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  69938. }
  69939. /**
  69940. * Set the motor values.
  69941. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69942. * @param {number} force the force to apply
  69943. * @param {number} maxForce max force for this motor.
  69944. * @param {motorIndex} the motor's index, 0 or 1.
  69945. */
  69946. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  69947. if (motorIndex === void 0) { motorIndex = 0; }
  69948. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  69949. };
  69950. /**
  69951. * Set the motor limits.
  69952. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69953. * @param {number} upperLimit the upper limit
  69954. * @param {number} lowerLimit lower limit
  69955. * @param {motorIndex} the motor's index, 0 or 1.
  69956. */
  69957. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  69958. if (motorIndex === void 0) { motorIndex = 0; }
  69959. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  69960. };
  69961. return Hinge2Joint;
  69962. }(MotorEnabledJoint));
  69963. BABYLON.Hinge2Joint = Hinge2Joint;
  69964. })(BABYLON || (BABYLON = {}));
  69965. //# sourceMappingURL=babylon.physicsJoint.js.map
  69966. var BABYLON;
  69967. (function (BABYLON) {
  69968. var PhysicsImpostor = /** @class */ (function () {
  69969. function PhysicsImpostor(object, type, _options, _scene) {
  69970. if (_options === void 0) { _options = { mass: 0 }; }
  69971. var _this = this;
  69972. this.object = object;
  69973. this.type = type;
  69974. this._options = _options;
  69975. this._scene = _scene;
  69976. this._bodyUpdateRequired = false;
  69977. this._onBeforePhysicsStepCallbacks = new Array();
  69978. this._onAfterPhysicsStepCallbacks = new Array();
  69979. this._onPhysicsCollideCallbacks = [];
  69980. this._deltaPosition = BABYLON.Vector3.Zero();
  69981. this._isDisposed = false;
  69982. //temp variables for parent rotation calculations
  69983. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  69984. this._tmpQuat = new BABYLON.Quaternion();
  69985. this._tmpQuat2 = new BABYLON.Quaternion();
  69986. /**
  69987. * this function is executed by the physics engine.
  69988. */
  69989. this.beforeStep = function () {
  69990. if (!_this._physicsEngine) {
  69991. return;
  69992. }
  69993. _this.object.translate(_this._deltaPosition, -1);
  69994. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  69995. _this.object.computeWorldMatrix(false);
  69996. if (_this.object.parent && _this.object.rotationQuaternion) {
  69997. _this.getParentsRotation();
  69998. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  69999. }
  70000. else {
  70001. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  70002. }
  70003. if (!_this._options.disableBidirectionalTransformation) {
  70004. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  70005. }
  70006. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  70007. func(_this);
  70008. });
  70009. };
  70010. /**
  70011. * this function is executed by the physics engine.
  70012. */
  70013. this.afterStep = function () {
  70014. if (!_this._physicsEngine) {
  70015. return;
  70016. }
  70017. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  70018. func(_this);
  70019. });
  70020. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  70021. // object has now its world rotation. needs to be converted to local.
  70022. if (_this.object.parent && _this.object.rotationQuaternion) {
  70023. _this.getParentsRotation();
  70024. _this._tmpQuat.conjugateInPlace();
  70025. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  70026. }
  70027. // take the position set and make it the absolute position of this object.
  70028. _this.object.setAbsolutePosition(_this.object.position);
  70029. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  70030. _this.object.translate(_this._deltaPosition, 1);
  70031. };
  70032. /**
  70033. * Legacy collision detection event support
  70034. */
  70035. this.onCollideEvent = null;
  70036. //event and body object due to cannon's event-based architecture.
  70037. this.onCollide = function (e) {
  70038. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  70039. return;
  70040. }
  70041. if (!_this._physicsEngine) {
  70042. return;
  70043. }
  70044. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  70045. if (otherImpostor) {
  70046. // Legacy collision detection event support
  70047. if (_this.onCollideEvent) {
  70048. _this.onCollideEvent(_this, otherImpostor);
  70049. }
  70050. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  70051. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  70052. }).forEach(function (obj) {
  70053. obj.callback(_this, otherImpostor);
  70054. });
  70055. }
  70056. };
  70057. //sanity check!
  70058. if (!this.object) {
  70059. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  70060. return;
  70061. }
  70062. //legacy support for old syntax.
  70063. if (!this._scene && object.getScene) {
  70064. this._scene = object.getScene();
  70065. }
  70066. if (!this._scene) {
  70067. return;
  70068. }
  70069. this._physicsEngine = this._scene.getPhysicsEngine();
  70070. if (!this._physicsEngine) {
  70071. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  70072. }
  70073. else {
  70074. //set the object's quaternion, if not set
  70075. if (!this.object.rotationQuaternion) {
  70076. if (this.object.rotation) {
  70077. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  70078. }
  70079. else {
  70080. this.object.rotationQuaternion = new BABYLON.Quaternion();
  70081. }
  70082. }
  70083. //default options params
  70084. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  70085. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  70086. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  70087. this._joints = [];
  70088. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  70089. if (!this.object.parent || this._options.ignoreParent) {
  70090. this._init();
  70091. }
  70092. else if (this.object.parent.physicsImpostor) {
  70093. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  70094. }
  70095. }
  70096. }
  70097. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  70098. get: function () {
  70099. return this._isDisposed;
  70100. },
  70101. enumerable: true,
  70102. configurable: true
  70103. });
  70104. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  70105. get: function () {
  70106. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  70107. },
  70108. set: function (value) {
  70109. this.setMass(value);
  70110. },
  70111. enumerable: true,
  70112. configurable: true
  70113. });
  70114. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  70115. get: function () {
  70116. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  70117. },
  70118. set: function (value) {
  70119. if (!this._physicsEngine) {
  70120. return;
  70121. }
  70122. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  70123. },
  70124. enumerable: true,
  70125. configurable: true
  70126. });
  70127. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  70128. get: function () {
  70129. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  70130. },
  70131. set: function (value) {
  70132. if (!this._physicsEngine) {
  70133. return;
  70134. }
  70135. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  70136. },
  70137. enumerable: true,
  70138. configurable: true
  70139. });
  70140. /**
  70141. * This function will completly initialize this impostor.
  70142. * It will create a new body - but only if this mesh has no parent.
  70143. * If it has, this impostor will not be used other than to define the impostor
  70144. * of the child mesh.
  70145. */
  70146. PhysicsImpostor.prototype._init = function () {
  70147. if (!this._physicsEngine) {
  70148. return;
  70149. }
  70150. this._physicsEngine.removeImpostor(this);
  70151. this.physicsBody = null;
  70152. this._parent = this._parent || this._getPhysicsParent();
  70153. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  70154. this._physicsEngine.addImpostor(this);
  70155. }
  70156. };
  70157. PhysicsImpostor.prototype._getPhysicsParent = function () {
  70158. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  70159. var parentMesh = this.object.parent;
  70160. return parentMesh.physicsImpostor;
  70161. }
  70162. return null;
  70163. };
  70164. /**
  70165. * Should a new body be generated.
  70166. */
  70167. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  70168. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  70169. };
  70170. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  70171. this.forceUpdate();
  70172. };
  70173. /**
  70174. * Force a regeneration of this or the parent's impostor's body.
  70175. * Use under cautious - This will remove all joints already implemented.
  70176. */
  70177. PhysicsImpostor.prototype.forceUpdate = function () {
  70178. this._init();
  70179. if (this.parent && !this._options.ignoreParent) {
  70180. this.parent.forceUpdate();
  70181. }
  70182. };
  70183. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  70184. /*public get mesh(): AbstractMesh {
  70185. return this._mesh;
  70186. }*/
  70187. /**
  70188. * Gets the body that holds this impostor. Either its own, or its parent.
  70189. */
  70190. get: function () {
  70191. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  70192. },
  70193. /**
  70194. * Set the physics body. Used mainly by the physics engine/plugin
  70195. */
  70196. set: function (physicsBody) {
  70197. if (this._physicsBody && this._physicsEngine) {
  70198. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  70199. }
  70200. this._physicsBody = physicsBody;
  70201. this.resetUpdateFlags();
  70202. },
  70203. enumerable: true,
  70204. configurable: true
  70205. });
  70206. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  70207. get: function () {
  70208. return !this._options.ignoreParent && this._parent ? this._parent : null;
  70209. },
  70210. set: function (value) {
  70211. this._parent = value;
  70212. },
  70213. enumerable: true,
  70214. configurable: true
  70215. });
  70216. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  70217. this._bodyUpdateRequired = false;
  70218. };
  70219. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  70220. if (this.object.getBoundingInfo) {
  70221. var q = this.object.rotationQuaternion;
  70222. //reset rotation
  70223. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  70224. //calculate the world matrix with no rotation
  70225. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70226. var boundingInfo = this.object.getBoundingInfo();
  70227. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  70228. //bring back the rotation
  70229. this.object.rotationQuaternion = q;
  70230. //calculate the world matrix with the new rotation
  70231. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70232. return size;
  70233. }
  70234. else {
  70235. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  70236. }
  70237. };
  70238. PhysicsImpostor.prototype.getObjectCenter = function () {
  70239. if (this.object.getBoundingInfo) {
  70240. var boundingInfo = this.object.getBoundingInfo();
  70241. return boundingInfo.boundingBox.centerWorld;
  70242. }
  70243. else {
  70244. return this.object.position;
  70245. }
  70246. };
  70247. /**
  70248. * Get a specific parametes from the options parameter.
  70249. */
  70250. PhysicsImpostor.prototype.getParam = function (paramName) {
  70251. return this._options[paramName];
  70252. };
  70253. /**
  70254. * Sets a specific parameter in the options given to the physics plugin
  70255. */
  70256. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  70257. this._options[paramName] = value;
  70258. this._bodyUpdateRequired = true;
  70259. };
  70260. /**
  70261. * Specifically change the body's mass option. Won't recreate the physics body object
  70262. */
  70263. PhysicsImpostor.prototype.setMass = function (mass) {
  70264. if (this.getParam("mass") !== mass) {
  70265. this.setParam("mass", mass);
  70266. }
  70267. if (this._physicsEngine) {
  70268. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  70269. }
  70270. };
  70271. PhysicsImpostor.prototype.getLinearVelocity = function () {
  70272. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  70273. };
  70274. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  70275. if (this._physicsEngine) {
  70276. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  70277. }
  70278. };
  70279. PhysicsImpostor.prototype.getAngularVelocity = function () {
  70280. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  70281. };
  70282. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  70283. if (this._physicsEngine) {
  70284. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  70285. }
  70286. };
  70287. /**
  70288. * Execute a function with the physics plugin native code.
  70289. * Provide a function the will have two variables - the world object and the physics body object.
  70290. */
  70291. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  70292. if (this._physicsEngine) {
  70293. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  70294. }
  70295. };
  70296. /**
  70297. * Register a function that will be executed before the physics world is stepping forward.
  70298. */
  70299. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  70300. this._onBeforePhysicsStepCallbacks.push(func);
  70301. };
  70302. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  70303. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  70304. if (index > -1) {
  70305. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  70306. }
  70307. else {
  70308. BABYLON.Tools.Warn("Function to remove was not found");
  70309. }
  70310. };
  70311. /**
  70312. * Register a function that will be executed after the physics step
  70313. */
  70314. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  70315. this._onAfterPhysicsStepCallbacks.push(func);
  70316. };
  70317. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  70318. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  70319. if (index > -1) {
  70320. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  70321. }
  70322. else {
  70323. BABYLON.Tools.Warn("Function to remove was not found");
  70324. }
  70325. };
  70326. /**
  70327. * register a function that will be executed when this impostor collides against a different body.
  70328. */
  70329. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  70330. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70331. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  70332. };
  70333. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  70334. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70335. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  70336. if (index > -1) {
  70337. this._onPhysicsCollideCallbacks.splice(index, 1);
  70338. }
  70339. else {
  70340. BABYLON.Tools.Warn("Function to remove was not found");
  70341. }
  70342. };
  70343. PhysicsImpostor.prototype.getParentsRotation = function () {
  70344. var parent = this.object.parent;
  70345. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  70346. while (parent) {
  70347. if (parent.rotationQuaternion) {
  70348. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  70349. }
  70350. else {
  70351. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  70352. }
  70353. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  70354. parent = parent.parent;
  70355. }
  70356. return this._tmpQuat;
  70357. };
  70358. /**
  70359. * Apply a force
  70360. */
  70361. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  70362. if (this._physicsEngine) {
  70363. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  70364. }
  70365. return this;
  70366. };
  70367. /**
  70368. * Apply an impulse
  70369. */
  70370. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  70371. if (this._physicsEngine) {
  70372. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  70373. }
  70374. return this;
  70375. };
  70376. /**
  70377. * A help function to create a joint.
  70378. */
  70379. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  70380. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  70381. this.addJoint(otherImpostor, joint);
  70382. return this;
  70383. };
  70384. /**
  70385. * Add a joint to this impostor with a different impostor.
  70386. */
  70387. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  70388. this._joints.push({
  70389. otherImpostor: otherImpostor,
  70390. joint: joint
  70391. });
  70392. if (this._physicsEngine) {
  70393. this._physicsEngine.addJoint(this, otherImpostor, joint);
  70394. }
  70395. return this;
  70396. };
  70397. /**
  70398. * Will keep this body still, in a sleep mode.
  70399. */
  70400. PhysicsImpostor.prototype.sleep = function () {
  70401. if (this._physicsEngine) {
  70402. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  70403. }
  70404. return this;
  70405. };
  70406. /**
  70407. * Wake the body up.
  70408. */
  70409. PhysicsImpostor.prototype.wakeUp = function () {
  70410. if (this._physicsEngine) {
  70411. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  70412. }
  70413. return this;
  70414. };
  70415. PhysicsImpostor.prototype.clone = function (newObject) {
  70416. if (!newObject)
  70417. return null;
  70418. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  70419. };
  70420. PhysicsImpostor.prototype.dispose = function () {
  70421. var _this = this;
  70422. //no dispose if no physics engine is available.
  70423. if (!this._physicsEngine) {
  70424. return;
  70425. }
  70426. this._joints.forEach(function (j) {
  70427. if (_this._physicsEngine) {
  70428. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  70429. }
  70430. });
  70431. //dispose the physics body
  70432. this._physicsEngine.removeImpostor(this);
  70433. if (this.parent) {
  70434. this.parent.forceUpdate();
  70435. }
  70436. else {
  70437. /*this._object.getChildMeshes().forEach(function(mesh) {
  70438. if (mesh.physicsImpostor) {
  70439. if (disposeChildren) {
  70440. mesh.physicsImpostor.dispose();
  70441. mesh.physicsImpostor = null;
  70442. }
  70443. }
  70444. })*/
  70445. }
  70446. this._isDisposed = true;
  70447. };
  70448. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70449. this._deltaPosition.copyFrom(position);
  70450. };
  70451. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70452. if (!this._deltaRotation) {
  70453. this._deltaRotation = new BABYLON.Quaternion();
  70454. }
  70455. this._deltaRotation.copyFrom(rotation);
  70456. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70457. };
  70458. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70459. if (this._physicsEngine) {
  70460. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70461. }
  70462. return this;
  70463. };
  70464. PhysicsImpostor.prototype.getRadius = function () {
  70465. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70466. };
  70467. /**
  70468. * Sync a bone with this impostor
  70469. * @param bone The bone to sync to the impostor.
  70470. * @param boneMesh The mesh that the bone is influencing.
  70471. * @param jointPivot The pivot of the joint / bone in local space.
  70472. * @param distToJoint Optional distance from the impostor to the joint.
  70473. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70474. */
  70475. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70476. var tempVec = PhysicsImpostor._tmpVecs[0];
  70477. var mesh = this.object;
  70478. if (mesh.rotationQuaternion) {
  70479. if (adjustRotation) {
  70480. var tempQuat = PhysicsImpostor._tmpQuat;
  70481. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70482. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70483. }
  70484. else {
  70485. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70486. }
  70487. }
  70488. tempVec.x = 0;
  70489. tempVec.y = 0;
  70490. tempVec.z = 0;
  70491. if (jointPivot) {
  70492. tempVec.x = jointPivot.x;
  70493. tempVec.y = jointPivot.y;
  70494. tempVec.z = jointPivot.z;
  70495. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70496. if (distToJoint === undefined || distToJoint === null) {
  70497. distToJoint = jointPivot.length();
  70498. }
  70499. tempVec.x *= distToJoint;
  70500. tempVec.y *= distToJoint;
  70501. tempVec.z *= distToJoint;
  70502. }
  70503. if (bone.getParent()) {
  70504. tempVec.addInPlace(mesh.getAbsolutePosition());
  70505. bone.setAbsolutePosition(tempVec, boneMesh);
  70506. }
  70507. else {
  70508. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70509. boneMesh.position.x -= tempVec.x;
  70510. boneMesh.position.y -= tempVec.y;
  70511. boneMesh.position.z -= tempVec.z;
  70512. }
  70513. };
  70514. /**
  70515. * Sync impostor to a bone
  70516. * @param bone The bone that the impostor will be synced to.
  70517. * @param boneMesh The mesh that the bone is influencing.
  70518. * @param jointPivot The pivot of the joint / bone in local space.
  70519. * @param distToJoint Optional distance from the impostor to the joint.
  70520. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70521. * @param boneAxis Optional vector3 axis the bone is aligned with
  70522. */
  70523. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70524. var mesh = this.object;
  70525. if (mesh.rotationQuaternion) {
  70526. if (adjustRotation) {
  70527. var tempQuat = PhysicsImpostor._tmpQuat;
  70528. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70529. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70530. }
  70531. else {
  70532. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70533. }
  70534. }
  70535. var pos = PhysicsImpostor._tmpVecs[0];
  70536. var boneDir = PhysicsImpostor._tmpVecs[1];
  70537. if (!boneAxis) {
  70538. boneAxis = PhysicsImpostor._tmpVecs[2];
  70539. boneAxis.x = 0;
  70540. boneAxis.y = 1;
  70541. boneAxis.z = 0;
  70542. }
  70543. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70544. bone.getAbsolutePositionToRef(boneMesh, pos);
  70545. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70546. distToJoint = jointPivot.length();
  70547. }
  70548. if (distToJoint !== undefined && distToJoint !== null) {
  70549. pos.x += boneDir.x * distToJoint;
  70550. pos.y += boneDir.y * distToJoint;
  70551. pos.z += boneDir.z * distToJoint;
  70552. }
  70553. mesh.setAbsolutePosition(pos);
  70554. };
  70555. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70556. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70557. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70558. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70559. //Impostor types
  70560. PhysicsImpostor.NoImpostor = 0;
  70561. PhysicsImpostor.SphereImpostor = 1;
  70562. PhysicsImpostor.BoxImpostor = 2;
  70563. PhysicsImpostor.PlaneImpostor = 3;
  70564. PhysicsImpostor.MeshImpostor = 4;
  70565. PhysicsImpostor.CylinderImpostor = 7;
  70566. PhysicsImpostor.ParticleImpostor = 8;
  70567. PhysicsImpostor.HeightmapImpostor = 9;
  70568. return PhysicsImpostor;
  70569. }());
  70570. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70571. })(BABYLON || (BABYLON = {}));
  70572. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70573. var BABYLON;
  70574. (function (BABYLON) {
  70575. var PhysicsEngine = /** @class */ (function () {
  70576. function PhysicsEngine(gravity, _physicsPlugin) {
  70577. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70578. this._physicsPlugin = _physicsPlugin;
  70579. //new methods and parameters
  70580. this._impostors = [];
  70581. this._joints = [];
  70582. if (!this._physicsPlugin.isSupported()) {
  70583. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70584. + "Please make sure it is included.");
  70585. }
  70586. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70587. this.setGravity(gravity);
  70588. this.setTimeStep();
  70589. }
  70590. PhysicsEngine.prototype.setGravity = function (gravity) {
  70591. this.gravity = gravity;
  70592. this._physicsPlugin.setGravity(this.gravity);
  70593. };
  70594. /**
  70595. * Set the time step of the physics engine.
  70596. * default is 1/60.
  70597. * To slow it down, enter 1/600 for example.
  70598. * To speed it up, 1/30
  70599. * @param {number} newTimeStep the new timestep to apply to this world.
  70600. */
  70601. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70602. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70603. this._physicsPlugin.setTimeStep(newTimeStep);
  70604. };
  70605. /**
  70606. * Get the time step of the physics engine.
  70607. */
  70608. PhysicsEngine.prototype.getTimeStep = function () {
  70609. return this._physicsPlugin.getTimeStep();
  70610. };
  70611. PhysicsEngine.prototype.dispose = function () {
  70612. this._impostors.forEach(function (impostor) {
  70613. impostor.dispose();
  70614. });
  70615. this._physicsPlugin.dispose();
  70616. };
  70617. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70618. return this._physicsPlugin.name;
  70619. };
  70620. /**
  70621. * Adding a new impostor for the impostor tracking.
  70622. * This will be done by the impostor itself.
  70623. * @param {PhysicsImpostor} impostor the impostor to add
  70624. */
  70625. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70626. impostor.uniqueId = this._impostors.push(impostor);
  70627. //if no parent, generate the body
  70628. if (!impostor.parent) {
  70629. this._physicsPlugin.generatePhysicsBody(impostor);
  70630. }
  70631. };
  70632. /**
  70633. * Remove an impostor from the engine.
  70634. * This impostor and its mesh will not longer be updated by the physics engine.
  70635. * @param {PhysicsImpostor} impostor the impostor to remove
  70636. */
  70637. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70638. var index = this._impostors.indexOf(impostor);
  70639. if (index > -1) {
  70640. var removed = this._impostors.splice(index, 1);
  70641. //Is it needed?
  70642. if (removed.length) {
  70643. //this will also remove it from the world.
  70644. removed[0].physicsBody = null;
  70645. }
  70646. }
  70647. };
  70648. /**
  70649. * Add a joint to the physics engine
  70650. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70651. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70652. * @param {PhysicsJoint} the joint that will connect both impostors.
  70653. */
  70654. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70655. var impostorJoint = {
  70656. mainImpostor: mainImpostor,
  70657. connectedImpostor: connectedImpostor,
  70658. joint: joint
  70659. };
  70660. joint.physicsPlugin = this._physicsPlugin;
  70661. this._joints.push(impostorJoint);
  70662. this._physicsPlugin.generateJoint(impostorJoint);
  70663. };
  70664. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  70665. var matchingJoints = this._joints.filter(function (impostorJoint) {
  70666. return (impostorJoint.connectedImpostor === connectedImpostor
  70667. && impostorJoint.joint === joint
  70668. && impostorJoint.mainImpostor === mainImpostor);
  70669. });
  70670. if (matchingJoints.length) {
  70671. this._physicsPlugin.removeJoint(matchingJoints[0]);
  70672. //TODO remove it from the list as well
  70673. }
  70674. };
  70675. /**
  70676. * Called by the scene. no need to call it.
  70677. */
  70678. PhysicsEngine.prototype._step = function (delta) {
  70679. var _this = this;
  70680. //check if any mesh has no body / requires an update
  70681. this._impostors.forEach(function (impostor) {
  70682. if (impostor.isBodyInitRequired()) {
  70683. _this._physicsPlugin.generatePhysicsBody(impostor);
  70684. }
  70685. });
  70686. if (delta > 0.1) {
  70687. delta = 0.1;
  70688. }
  70689. else if (delta <= 0) {
  70690. delta = 1.0 / 60.0;
  70691. }
  70692. this._physicsPlugin.executeStep(delta, this._impostors);
  70693. };
  70694. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  70695. return this._physicsPlugin;
  70696. };
  70697. PhysicsEngine.prototype.getImpostors = function () {
  70698. return this._impostors;
  70699. };
  70700. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  70701. for (var i = 0; i < this._impostors.length; ++i) {
  70702. if (this._impostors[i].object === object) {
  70703. return this._impostors[i];
  70704. }
  70705. }
  70706. return null;
  70707. };
  70708. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  70709. for (var i = 0; i < this._impostors.length; ++i) {
  70710. if (this._impostors[i].physicsBody === body) {
  70711. return this._impostors[i];
  70712. }
  70713. }
  70714. return null;
  70715. };
  70716. // Statics
  70717. PhysicsEngine.Epsilon = 0.001;
  70718. return PhysicsEngine;
  70719. }());
  70720. BABYLON.PhysicsEngine = PhysicsEngine;
  70721. })(BABYLON || (BABYLON = {}));
  70722. //# sourceMappingURL=babylon.physicsEngine.js.map
  70723. var BABYLON;
  70724. (function (BABYLON) {
  70725. var PhysicsHelper = /** @class */ (function () {
  70726. function PhysicsHelper(scene) {
  70727. this._scene = scene;
  70728. this._physicsEngine = this._scene.getPhysicsEngine();
  70729. if (!this._physicsEngine) {
  70730. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  70731. }
  70732. }
  70733. /**
  70734. * @param {Vector3} origin the origin of the explosion
  70735. * @param {number} radius the explosion radius
  70736. * @param {number} strength the explosion strength
  70737. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70738. */
  70739. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  70740. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70741. if (!this._physicsEngine) {
  70742. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  70743. return null;
  70744. }
  70745. var impostors = this._physicsEngine.getImpostors();
  70746. if (impostors.length === 0) {
  70747. return null;
  70748. }
  70749. var event = new PhysicsRadialExplosionEvent(this._scene);
  70750. impostors.forEach(function (impostor) {
  70751. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70752. if (!impostorForceAndContactPoint) {
  70753. return;
  70754. }
  70755. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70756. });
  70757. event.dispose(false);
  70758. return event;
  70759. };
  70760. /**
  70761. * @param {Vector3} origin the origin of the explosion
  70762. * @param {number} radius the explosion radius
  70763. * @param {number} strength the explosion strength
  70764. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70765. */
  70766. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  70767. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70768. if (!this._physicsEngine) {
  70769. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70770. return null;
  70771. }
  70772. var impostors = this._physicsEngine.getImpostors();
  70773. if (impostors.length === 0) {
  70774. return null;
  70775. }
  70776. var event = new PhysicsRadialExplosionEvent(this._scene);
  70777. impostors.forEach(function (impostor) {
  70778. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70779. if (!impostorForceAndContactPoint) {
  70780. return;
  70781. }
  70782. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70783. });
  70784. event.dispose(false);
  70785. return event;
  70786. };
  70787. /**
  70788. * @param {Vector3} origin the origin of the explosion
  70789. * @param {number} radius the explosion radius
  70790. * @param {number} strength the explosion strength
  70791. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70792. */
  70793. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  70794. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70795. if (!this._physicsEngine) {
  70796. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70797. return null;
  70798. }
  70799. var impostors = this._physicsEngine.getImpostors();
  70800. if (impostors.length === 0) {
  70801. return null;
  70802. }
  70803. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  70804. event.dispose(false);
  70805. return event;
  70806. };
  70807. /**
  70808. * @param {Vector3} origin the origin of the updraft
  70809. * @param {number} radius the radius of the updraft
  70810. * @param {number} strength the strength of the updraft
  70811. * @param {number} height the height of the updraft
  70812. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  70813. */
  70814. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  70815. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  70816. if (!this._physicsEngine) {
  70817. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70818. return null;
  70819. }
  70820. if (this._physicsEngine.getImpostors().length === 0) {
  70821. return null;
  70822. }
  70823. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  70824. event.dispose(false);
  70825. return event;
  70826. };
  70827. /**
  70828. * @param {Vector3} origin the of the vortex
  70829. * @param {number} radius the radius of the vortex
  70830. * @param {number} strength the strength of the vortex
  70831. * @param {number} height the height of the vortex
  70832. */
  70833. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  70834. if (!this._physicsEngine) {
  70835. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70836. return null;
  70837. }
  70838. if (this._physicsEngine.getImpostors().length === 0) {
  70839. return null;
  70840. }
  70841. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  70842. event.dispose(false);
  70843. return event;
  70844. };
  70845. return PhysicsHelper;
  70846. }());
  70847. BABYLON.PhysicsHelper = PhysicsHelper;
  70848. /***** Radial explosion *****/
  70849. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  70850. function PhysicsRadialExplosionEvent(scene) {
  70851. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  70852. this._rays = [];
  70853. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  70854. this._scene = scene;
  70855. }
  70856. /**
  70857. * Returns the data related to the radial explosion event (sphere & rays).
  70858. * @returns {PhysicsRadialExplosionEventData}
  70859. */
  70860. PhysicsRadialExplosionEvent.prototype.getData = function () {
  70861. this._dataFetched = true;
  70862. return {
  70863. sphere: this._sphere,
  70864. rays: this._rays,
  70865. };
  70866. };
  70867. /**
  70868. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  70869. * @param impostor
  70870. * @param {Vector3} origin the origin of the explosion
  70871. * @param {number} radius the explosion radius
  70872. * @param {number} strength the explosion strength
  70873. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  70874. * @returns {Nullable<PhysicsForceAndContactPoint>}
  70875. */
  70876. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  70877. if (impostor.mass === 0) {
  70878. return null;
  70879. }
  70880. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  70881. return null;
  70882. }
  70883. if (impostor.object.getClassName() !== 'Mesh') {
  70884. return null;
  70885. }
  70886. var impostorObject = impostor.object;
  70887. var impostorObjectCenter = impostor.getObjectCenter();
  70888. var direction = impostorObjectCenter.subtract(origin);
  70889. var ray = new BABYLON.Ray(origin, direction, radius);
  70890. this._rays.push(ray);
  70891. var hit = ray.intersectsMesh(impostorObject);
  70892. var contactPoint = hit.pickedPoint;
  70893. if (!contactPoint) {
  70894. return null;
  70895. }
  70896. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  70897. if (distanceFromOrigin > radius) {
  70898. return null;
  70899. }
  70900. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  70901. ? strength
  70902. : strength * (1 - (distanceFromOrigin / radius));
  70903. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  70904. return { force: force, contactPoint: contactPoint };
  70905. };
  70906. /**
  70907. * Disposes the sphere.
  70908. * @param {bolean} force
  70909. */
  70910. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  70911. var _this = this;
  70912. if (force === void 0) { force = true; }
  70913. if (force) {
  70914. this._sphere.dispose();
  70915. }
  70916. else {
  70917. setTimeout(function () {
  70918. if (!_this._dataFetched) {
  70919. _this._sphere.dispose();
  70920. }
  70921. }, 0);
  70922. }
  70923. };
  70924. /*** Helpers ***/
  70925. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  70926. if (!this._sphere) {
  70927. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  70928. this._sphere.isVisible = false;
  70929. }
  70930. };
  70931. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  70932. var impostorObject = impostor.object;
  70933. this._prepareSphere();
  70934. this._sphere.position = origin;
  70935. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  70936. this._sphere._updateBoundingInfo();
  70937. this._sphere.computeWorldMatrix(true);
  70938. return this._sphere.intersectsMesh(impostorObject, true);
  70939. };
  70940. return PhysicsRadialExplosionEvent;
  70941. }());
  70942. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  70943. /***** Gravitational Field *****/
  70944. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  70945. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  70946. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70947. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  70948. this._physicsHelper = physicsHelper;
  70949. this._scene = scene;
  70950. this._origin = origin;
  70951. this._radius = radius;
  70952. this._strength = strength;
  70953. this._falloff = falloff;
  70954. this._tickCallback = this._tick.bind(this);
  70955. }
  70956. /**
  70957. * Returns the data related to the gravitational field event (sphere).
  70958. * @returns {PhysicsGravitationalFieldEventData}
  70959. */
  70960. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  70961. this._dataFetched = true;
  70962. return {
  70963. sphere: this._sphere,
  70964. };
  70965. };
  70966. /**
  70967. * Enables the gravitational field.
  70968. */
  70969. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  70970. this._tickCallback.call(this);
  70971. this._scene.registerBeforeRender(this._tickCallback);
  70972. };
  70973. /**
  70974. * Disables the gravitational field.
  70975. */
  70976. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  70977. this._scene.unregisterBeforeRender(this._tickCallback);
  70978. };
  70979. /**
  70980. * Disposes the sphere.
  70981. * @param {bolean} force
  70982. */
  70983. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  70984. var _this = this;
  70985. if (force === void 0) { force = true; }
  70986. if (force) {
  70987. this._sphere.dispose();
  70988. }
  70989. else {
  70990. setTimeout(function () {
  70991. if (!_this._dataFetched) {
  70992. _this._sphere.dispose();
  70993. }
  70994. }, 0);
  70995. }
  70996. };
  70997. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  70998. // Since the params won't change, we fetch the event only once
  70999. if (this._sphere) {
  71000. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71001. }
  71002. else {
  71003. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71004. if (radialExplosionEvent) {
  71005. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  71006. }
  71007. }
  71008. };
  71009. return PhysicsGravitationalFieldEvent;
  71010. }());
  71011. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  71012. /***** Updraft *****/
  71013. var PhysicsUpdraftEvent = /** @class */ (function () {
  71014. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  71015. this._scene = _scene;
  71016. this._origin = _origin;
  71017. this._radius = _radius;
  71018. this._strength = _strength;
  71019. this._height = _height;
  71020. this._updraftMode = _updraftMode;
  71021. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71022. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  71023. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71024. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71025. this._physicsEngine = this._scene.getPhysicsEngine();
  71026. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71027. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71028. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71029. this._originDirection = this._origin.subtract(this._originTop).normalize();
  71030. }
  71031. this._tickCallback = this._tick.bind(this);
  71032. }
  71033. /**
  71034. * Returns the data related to the updraft event (cylinder).
  71035. * @returns {PhysicsUpdraftEventData}
  71036. */
  71037. PhysicsUpdraftEvent.prototype.getData = function () {
  71038. this._dataFetched = true;
  71039. return {
  71040. cylinder: this._cylinder,
  71041. };
  71042. };
  71043. /**
  71044. * Enables the updraft.
  71045. */
  71046. PhysicsUpdraftEvent.prototype.enable = function () {
  71047. this._tickCallback.call(this);
  71048. this._scene.registerBeforeRender(this._tickCallback);
  71049. };
  71050. /**
  71051. * Disables the cortex.
  71052. */
  71053. PhysicsUpdraftEvent.prototype.disable = function () {
  71054. this._scene.unregisterBeforeRender(this._tickCallback);
  71055. };
  71056. /**
  71057. * Disposes the sphere.
  71058. * @param {bolean} force
  71059. */
  71060. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  71061. var _this = this;
  71062. if (force === void 0) { force = true; }
  71063. if (force) {
  71064. this._cylinder.dispose();
  71065. }
  71066. else {
  71067. setTimeout(function () {
  71068. if (!_this._dataFetched) {
  71069. _this._cylinder.dispose();
  71070. }
  71071. }, 0);
  71072. }
  71073. };
  71074. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71075. if (impostor.mass === 0) {
  71076. return null;
  71077. }
  71078. if (!this._intersectsWithCylinder(impostor)) {
  71079. return null;
  71080. }
  71081. var impostorObjectCenter = impostor.getObjectCenter();
  71082. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71083. var direction = this._originDirection;
  71084. }
  71085. else {
  71086. var direction = impostorObjectCenter.subtract(this._originTop);
  71087. }
  71088. var multiplier = this._strength * -1;
  71089. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71090. return { force: force, contactPoint: impostorObjectCenter };
  71091. };
  71092. PhysicsUpdraftEvent.prototype._tick = function () {
  71093. var _this = this;
  71094. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71095. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71096. if (!impostorForceAndContactPoint) {
  71097. return;
  71098. }
  71099. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71100. });
  71101. };
  71102. /*** Helpers ***/
  71103. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  71104. if (!this._cylinder) {
  71105. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  71106. height: this._height,
  71107. diameter: this._radius * 2,
  71108. }, this._scene);
  71109. this._cylinder.isVisible = false;
  71110. }
  71111. };
  71112. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  71113. var impostorObject = impostor.object;
  71114. this._prepareCylinder();
  71115. this._cylinder.position = this._cylinderPosition;
  71116. return this._cylinder.intersectsMesh(impostorObject, true);
  71117. };
  71118. return PhysicsUpdraftEvent;
  71119. }());
  71120. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  71121. /***** Vortex *****/
  71122. var PhysicsVortexEvent = /** @class */ (function () {
  71123. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  71124. this._scene = _scene;
  71125. this._origin = _origin;
  71126. this._radius = _radius;
  71127. this._strength = _strength;
  71128. this._height = _height;
  71129. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71130. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  71131. this._updraftMultiplier = 0.02;
  71132. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71133. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71134. this._physicsEngine = this._scene.getPhysicsEngine();
  71135. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71136. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71137. this._tickCallback = this._tick.bind(this);
  71138. }
  71139. /**
  71140. * Returns the data related to the vortex event (cylinder).
  71141. * @returns {PhysicsVortexEventData}
  71142. */
  71143. PhysicsVortexEvent.prototype.getData = function () {
  71144. this._dataFetched = true;
  71145. return {
  71146. cylinder: this._cylinder,
  71147. };
  71148. };
  71149. /**
  71150. * Enables the vortex.
  71151. */
  71152. PhysicsVortexEvent.prototype.enable = function () {
  71153. this._tickCallback.call(this);
  71154. this._scene.registerBeforeRender(this._tickCallback);
  71155. };
  71156. /**
  71157. * Disables the cortex.
  71158. */
  71159. PhysicsVortexEvent.prototype.disable = function () {
  71160. this._scene.unregisterBeforeRender(this._tickCallback);
  71161. };
  71162. /**
  71163. * Disposes the sphere.
  71164. * @param {bolean} force
  71165. */
  71166. PhysicsVortexEvent.prototype.dispose = function (force) {
  71167. var _this = this;
  71168. if (force === void 0) { force = true; }
  71169. if (force) {
  71170. this._cylinder.dispose();
  71171. }
  71172. else {
  71173. setTimeout(function () {
  71174. if (!_this._dataFetched) {
  71175. _this._cylinder.dispose();
  71176. }
  71177. }, 0);
  71178. }
  71179. };
  71180. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71181. if (impostor.mass === 0) {
  71182. return null;
  71183. }
  71184. if (!this._intersectsWithCylinder(impostor)) {
  71185. return null;
  71186. }
  71187. if (impostor.object.getClassName() !== 'Mesh') {
  71188. return null;
  71189. }
  71190. var impostorObject = impostor.object;
  71191. var impostorObjectCenter = impostor.getObjectCenter();
  71192. 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)
  71193. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  71194. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  71195. var hit = ray.intersectsMesh(impostorObject);
  71196. var contactPoint = hit.pickedPoint;
  71197. if (!contactPoint) {
  71198. return null;
  71199. }
  71200. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  71201. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  71202. var directionToOrigin = contactPoint.normalize();
  71203. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71204. directionToOrigin = directionToOrigin.negate();
  71205. }
  71206. // TODO: find a more physically based solution
  71207. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71208. var forceX = directionToOrigin.x * this._strength / 8;
  71209. var forceY = directionToOrigin.y * this._updraftMultiplier;
  71210. var forceZ = directionToOrigin.z * this._strength / 8;
  71211. }
  71212. else {
  71213. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  71214. var forceY = this._originTop.y * this._updraftMultiplier;
  71215. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  71216. }
  71217. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  71218. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  71219. return { force: force, contactPoint: impostorObjectCenter };
  71220. };
  71221. PhysicsVortexEvent.prototype._tick = function () {
  71222. var _this = this;
  71223. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71224. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71225. if (!impostorForceAndContactPoint) {
  71226. return;
  71227. }
  71228. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71229. });
  71230. };
  71231. /*** Helpers ***/
  71232. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  71233. if (!this._cylinder) {
  71234. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  71235. height: this._height,
  71236. diameter: this._radius * 2,
  71237. }, this._scene);
  71238. this._cylinder.isVisible = false;
  71239. }
  71240. };
  71241. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  71242. var impostorObject = impostor.object;
  71243. this._prepareCylinder();
  71244. this._cylinder.position = this._cylinderPosition;
  71245. return this._cylinder.intersectsMesh(impostorObject, true);
  71246. };
  71247. return PhysicsVortexEvent;
  71248. }());
  71249. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  71250. /***** Enums *****/
  71251. /**
  71252. * The strenght of the force in correspondence to the distance of the affected object
  71253. */
  71254. var PhysicsRadialImpulseFalloff;
  71255. (function (PhysicsRadialImpulseFalloff) {
  71256. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  71257. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  71258. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  71259. /**
  71260. * The strenght of the force in correspondence to the distance of the affected object
  71261. */
  71262. var PhysicsUpdraftMode;
  71263. (function (PhysicsUpdraftMode) {
  71264. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  71265. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  71266. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  71267. })(BABYLON || (BABYLON = {}));
  71268. //# sourceMappingURL=babylon.physicsHelper.js.map
  71269. var BABYLON;
  71270. (function (BABYLON) {
  71271. var CannonJSPlugin = /** @class */ (function () {
  71272. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  71273. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  71274. if (iterations === void 0) { iterations = 10; }
  71275. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  71276. this.name = "CannonJSPlugin";
  71277. this._physicsMaterials = new Array();
  71278. this._fixedTimeStep = 1 / 60;
  71279. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  71280. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  71281. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  71282. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  71283. this._tmpPosition = BABYLON.Vector3.Zero();
  71284. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  71285. this._tmpUnityRotation = new BABYLON.Quaternion();
  71286. if (!this.isSupported()) {
  71287. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  71288. return;
  71289. }
  71290. this._extendNamespace();
  71291. this.world = new this.BJSCANNON.World();
  71292. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  71293. this.world.solver.iterations = iterations;
  71294. }
  71295. CannonJSPlugin.prototype.setGravity = function (gravity) {
  71296. this.world.gravity.copy(gravity);
  71297. };
  71298. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  71299. this._fixedTimeStep = timeStep;
  71300. };
  71301. CannonJSPlugin.prototype.getTimeStep = function () {
  71302. return this._fixedTimeStep;
  71303. };
  71304. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  71305. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  71306. };
  71307. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71308. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71309. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71310. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  71311. };
  71312. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71313. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71314. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71315. impostor.physicsBody.applyForce(impulse, worldPoint);
  71316. };
  71317. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71318. //parent-child relationship. Does this impostor has a parent impostor?
  71319. if (impostor.parent) {
  71320. if (impostor.physicsBody) {
  71321. this.removePhysicsBody(impostor);
  71322. //TODO is that needed?
  71323. impostor.forceUpdate();
  71324. }
  71325. return;
  71326. }
  71327. //should a new body be created for this impostor?
  71328. if (impostor.isBodyInitRequired()) {
  71329. var shape = this._createShape(impostor);
  71330. //unregister events, if body is being changed
  71331. var oldBody = impostor.physicsBody;
  71332. if (oldBody) {
  71333. this.removePhysicsBody(impostor);
  71334. }
  71335. //create the body and material
  71336. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  71337. var bodyCreationObject = {
  71338. mass: impostor.getParam("mass"),
  71339. material: material
  71340. };
  71341. // A simple extend, in case native options were used.
  71342. var nativeOptions = impostor.getParam("nativeOptions");
  71343. for (var key in nativeOptions) {
  71344. if (nativeOptions.hasOwnProperty(key)) {
  71345. bodyCreationObject[key] = nativeOptions[key];
  71346. }
  71347. }
  71348. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  71349. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  71350. this.world.addEventListener("preStep", impostor.beforeStep);
  71351. this.world.addEventListener("postStep", impostor.afterStep);
  71352. impostor.physicsBody.addShape(shape);
  71353. this.world.add(impostor.physicsBody);
  71354. //try to keep the body moving in the right direction by taking old properties.
  71355. //Should be tested!
  71356. if (oldBody) {
  71357. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  71358. impostor.physicsBody[param].copy(oldBody[param]);
  71359. });
  71360. }
  71361. this._processChildMeshes(impostor);
  71362. }
  71363. //now update the body's transformation
  71364. this._updatePhysicsBodyTransformation(impostor);
  71365. };
  71366. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  71367. var _this = this;
  71368. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  71369. var currentRotation = mainImpostor.object.rotationQuaternion;
  71370. if (meshChildren.length) {
  71371. var processMesh = function (localPosition, mesh) {
  71372. if (!currentRotation || !mesh.rotationQuaternion) {
  71373. return;
  71374. }
  71375. var childImpostor = mesh.getPhysicsImpostor();
  71376. if (childImpostor) {
  71377. var parent = childImpostor.parent;
  71378. if (parent !== mainImpostor) {
  71379. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  71380. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  71381. if (childImpostor.physicsBody) {
  71382. _this.removePhysicsBody(childImpostor);
  71383. childImpostor.physicsBody = null;
  71384. }
  71385. childImpostor.parent = mainImpostor;
  71386. childImpostor.resetUpdateFlags();
  71387. 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));
  71388. //Add the mass of the children.
  71389. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  71390. }
  71391. }
  71392. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  71393. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  71394. };
  71395. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  71396. }
  71397. };
  71398. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71399. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  71400. this.world.removeEventListener("preStep", impostor.beforeStep);
  71401. this.world.removeEventListener("postStep", impostor.afterStep);
  71402. this.world.remove(impostor.physicsBody);
  71403. };
  71404. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71405. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71406. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71407. if (!mainBody || !connectedBody) {
  71408. return;
  71409. }
  71410. var constraint;
  71411. var jointData = impostorJoint.joint.jointData;
  71412. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  71413. var constraintData = {
  71414. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  71415. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  71416. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  71417. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  71418. maxForce: jointData.nativeParams.maxForce,
  71419. collideConnected: !!jointData.collision
  71420. };
  71421. switch (impostorJoint.joint.type) {
  71422. case BABYLON.PhysicsJoint.HingeJoint:
  71423. case BABYLON.PhysicsJoint.Hinge2Joint:
  71424. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  71425. break;
  71426. case BABYLON.PhysicsJoint.DistanceJoint:
  71427. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  71428. break;
  71429. case BABYLON.PhysicsJoint.SpringJoint:
  71430. var springData = jointData;
  71431. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  71432. restLength: springData.length,
  71433. stiffness: springData.stiffness,
  71434. damping: springData.damping,
  71435. localAnchorA: constraintData.pivotA,
  71436. localAnchorB: constraintData.pivotB
  71437. });
  71438. break;
  71439. case BABYLON.PhysicsJoint.LockJoint:
  71440. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71441. break;
  71442. case BABYLON.PhysicsJoint.PointToPointJoint:
  71443. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71444. default:
  71445. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71446. break;
  71447. }
  71448. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71449. constraint.collideConnected = !!jointData.collision;
  71450. impostorJoint.joint.physicsJoint = constraint;
  71451. //don't add spring as constraint, as it is not one.
  71452. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71453. this.world.addConstraint(constraint);
  71454. }
  71455. else {
  71456. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71457. constraint.applyForce();
  71458. });
  71459. }
  71460. };
  71461. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71462. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71463. };
  71464. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71465. var index;
  71466. var mat;
  71467. for (index = 0; index < this._physicsMaterials.length; index++) {
  71468. mat = this._physicsMaterials[index];
  71469. if (mat.friction === friction && mat.restitution === restitution) {
  71470. return mat;
  71471. }
  71472. }
  71473. var currentMat = new this.BJSCANNON.Material(name);
  71474. currentMat.friction = friction;
  71475. currentMat.restitution = restitution;
  71476. this._physicsMaterials.push(currentMat);
  71477. return currentMat;
  71478. };
  71479. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71480. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71481. };
  71482. CannonJSPlugin.prototype._createShape = function (impostor) {
  71483. var object = impostor.object;
  71484. var returnValue;
  71485. var extendSize = impostor.getObjectExtendSize();
  71486. switch (impostor.type) {
  71487. case BABYLON.PhysicsImpostor.SphereImpostor:
  71488. var radiusX = extendSize.x;
  71489. var radiusY = extendSize.y;
  71490. var radiusZ = extendSize.z;
  71491. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71492. break;
  71493. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71494. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71495. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71496. break;
  71497. case BABYLON.PhysicsImpostor.BoxImpostor:
  71498. var box = extendSize.scale(0.5);
  71499. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71500. break;
  71501. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71502. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71503. returnValue = new this.BJSCANNON.Plane();
  71504. break;
  71505. case BABYLON.PhysicsImpostor.MeshImpostor:
  71506. // should transform the vertex data to world coordinates!!
  71507. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71508. var rawFaces = object.getIndices ? object.getIndices() : [];
  71509. if (!rawVerts)
  71510. return;
  71511. // get only scale! so the object could transform correctly.
  71512. var oldPosition = object.position.clone();
  71513. var oldRotation = object.rotation && object.rotation.clone();
  71514. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71515. object.position.copyFromFloats(0, 0, 0);
  71516. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71517. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71518. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71519. var transform = object.computeWorldMatrix(true);
  71520. // convert rawVerts to object space
  71521. var temp = new Array();
  71522. var index;
  71523. for (index = 0; index < rawVerts.length; index += 3) {
  71524. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71525. }
  71526. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71527. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71528. //now set back the transformation!
  71529. object.position.copyFrom(oldPosition);
  71530. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71531. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71532. break;
  71533. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71534. var oldPosition2 = object.position.clone();
  71535. var oldRotation2 = object.rotation && object.rotation.clone();
  71536. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71537. object.position.copyFromFloats(0, 0, 0);
  71538. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71539. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71540. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71541. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71542. returnValue = this._createHeightmap(object);
  71543. object.position.copyFrom(oldPosition2);
  71544. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71545. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71546. object.computeWorldMatrix(true);
  71547. break;
  71548. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71549. returnValue = new this.BJSCANNON.Particle();
  71550. break;
  71551. }
  71552. return returnValue;
  71553. };
  71554. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71555. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71556. var transform = object.computeWorldMatrix(true);
  71557. // convert rawVerts to object space
  71558. var temp = new Array();
  71559. var index;
  71560. for (index = 0; index < pos.length; index += 3) {
  71561. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71562. }
  71563. pos = temp;
  71564. var matrix = new Array();
  71565. //For now pointDepth will not be used and will be automatically calculated.
  71566. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71567. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71568. var boundingInfo = object.getBoundingInfo();
  71569. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71570. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71571. var elementSize = dim * 2 / arraySize;
  71572. for (var i = 0; i < pos.length; i = i + 3) {
  71573. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71574. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71575. var y = -pos[i + 2] + minY;
  71576. if (!matrix[x]) {
  71577. matrix[x] = [];
  71578. }
  71579. if (!matrix[x][z]) {
  71580. matrix[x][z] = y;
  71581. }
  71582. matrix[x][z] = Math.max(y, matrix[x][z]);
  71583. }
  71584. for (var x = 0; x <= arraySize; ++x) {
  71585. if (!matrix[x]) {
  71586. var loc = 1;
  71587. while (!matrix[(x + loc) % arraySize]) {
  71588. loc++;
  71589. }
  71590. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71591. //console.log("missing x", x);
  71592. }
  71593. for (var z = 0; z <= arraySize; ++z) {
  71594. if (!matrix[x][z]) {
  71595. var loc = 1;
  71596. var newValue;
  71597. while (newValue === undefined) {
  71598. newValue = matrix[x][(z + loc++) % arraySize];
  71599. }
  71600. matrix[x][z] = newValue;
  71601. }
  71602. }
  71603. }
  71604. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71605. elementSize: elementSize
  71606. });
  71607. //For future reference, needed for body transformation
  71608. shape.minY = minY;
  71609. return shape;
  71610. };
  71611. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71612. var object = impostor.object;
  71613. //make sure it is updated...
  71614. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71615. // The delta between the mesh position and the mesh bounding box center
  71616. var bInfo = object.getBoundingInfo();
  71617. if (!bInfo)
  71618. return;
  71619. var center = impostor.getObjectCenter();
  71620. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71621. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71622. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71623. this._tmpPosition.copyFrom(center);
  71624. var quaternion = object.rotationQuaternion;
  71625. if (!quaternion) {
  71626. return;
  71627. }
  71628. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71629. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71630. //-90 DEG in X, precalculated
  71631. quaternion = quaternion.multiply(this._minus90X);
  71632. //Invert! (Precalculated, 90 deg in X)
  71633. //No need to clone. this will never change.
  71634. impostor.setDeltaRotation(this._plus90X);
  71635. }
  71636. //If it is a heightfield, if should be centered.
  71637. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71638. var mesh = object;
  71639. var boundingInfo = mesh.getBoundingInfo();
  71640. //calculate the correct body position:
  71641. var rotationQuaternion = mesh.rotationQuaternion;
  71642. mesh.rotationQuaternion = this._tmpUnityRotation;
  71643. mesh.computeWorldMatrix(true);
  71644. //get original center with no rotation
  71645. var c = center.clone();
  71646. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71647. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71648. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71649. mesh.setPivotMatrix(p);
  71650. mesh.computeWorldMatrix(true);
  71651. //calculate the translation
  71652. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71653. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71654. //add it inverted to the delta
  71655. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71656. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71657. //rotation is back
  71658. mesh.rotationQuaternion = rotationQuaternion;
  71659. mesh.setPivotMatrix(oldPivot);
  71660. mesh.computeWorldMatrix(true);
  71661. }
  71662. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71663. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71664. //this._tmpPosition.copyFrom(object.position);
  71665. }
  71666. impostor.setDeltaPosition(this._tmpDeltaPosition);
  71667. //Now update the impostor object
  71668. impostor.physicsBody.position.copy(this._tmpPosition);
  71669. impostor.physicsBody.quaternion.copy(quaternion);
  71670. };
  71671. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71672. impostor.object.position.copyFrom(impostor.physicsBody.position);
  71673. if (impostor.object.rotationQuaternion) {
  71674. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  71675. }
  71676. };
  71677. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71678. impostor.physicsBody.position.copy(newPosition);
  71679. impostor.physicsBody.quaternion.copy(newRotation);
  71680. };
  71681. CannonJSPlugin.prototype.isSupported = function () {
  71682. return this.BJSCANNON !== undefined;
  71683. };
  71684. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71685. impostor.physicsBody.velocity.copy(velocity);
  71686. };
  71687. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71688. impostor.physicsBody.angularVelocity.copy(velocity);
  71689. };
  71690. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71691. var v = impostor.physicsBody.velocity;
  71692. if (!v) {
  71693. return null;
  71694. }
  71695. return new BABYLON.Vector3(v.x, v.y, v.z);
  71696. };
  71697. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71698. var v = impostor.physicsBody.angularVelocity;
  71699. if (!v) {
  71700. return null;
  71701. }
  71702. return new BABYLON.Vector3(v.x, v.y, v.z);
  71703. };
  71704. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71705. impostor.physicsBody.mass = mass;
  71706. impostor.physicsBody.updateMassProperties();
  71707. };
  71708. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  71709. return impostor.physicsBody.mass;
  71710. };
  71711. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  71712. return impostor.physicsBody.material.friction;
  71713. };
  71714. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71715. impostor.physicsBody.material.friction = friction;
  71716. };
  71717. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71718. return impostor.physicsBody.material.restitution;
  71719. };
  71720. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71721. impostor.physicsBody.material.restitution = restitution;
  71722. };
  71723. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  71724. impostor.physicsBody.sleep();
  71725. };
  71726. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  71727. impostor.physicsBody.wakeUp();
  71728. };
  71729. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71730. joint.physicsJoint.distance = maxDistance;
  71731. };
  71732. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71733. // if (!motorIndex) {
  71734. // joint.physicsJoint.enableMotor();
  71735. // }
  71736. // }
  71737. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71738. // if (!motorIndex) {
  71739. // joint.physicsJoint.disableMotor();
  71740. // }
  71741. // }
  71742. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71743. if (!motorIndex) {
  71744. joint.physicsJoint.enableMotor();
  71745. joint.physicsJoint.setMotorSpeed(speed);
  71746. if (maxForce) {
  71747. this.setLimit(joint, maxForce);
  71748. }
  71749. }
  71750. };
  71751. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  71752. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  71753. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  71754. };
  71755. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71756. var body = impostor.physicsBody;
  71757. mesh.position.x = body.position.x;
  71758. mesh.position.y = body.position.y;
  71759. mesh.position.z = body.position.z;
  71760. if (mesh.rotationQuaternion) {
  71761. mesh.rotationQuaternion.x = body.quaternion.x;
  71762. mesh.rotationQuaternion.y = body.quaternion.y;
  71763. mesh.rotationQuaternion.z = body.quaternion.z;
  71764. mesh.rotationQuaternion.w = body.quaternion.w;
  71765. }
  71766. };
  71767. CannonJSPlugin.prototype.getRadius = function (impostor) {
  71768. var shape = impostor.physicsBody.shapes[0];
  71769. return shape.boundingSphereRadius;
  71770. };
  71771. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71772. var shape = impostor.physicsBody.shapes[0];
  71773. result.x = shape.halfExtents.x * 2;
  71774. result.y = shape.halfExtents.y * 2;
  71775. result.z = shape.halfExtents.z * 2;
  71776. };
  71777. CannonJSPlugin.prototype.dispose = function () {
  71778. };
  71779. CannonJSPlugin.prototype._extendNamespace = function () {
  71780. //this will force cannon to execute at least one step when using interpolation
  71781. var step_tmp1 = new this.BJSCANNON.Vec3();
  71782. var Engine = this.BJSCANNON;
  71783. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  71784. maxSubSteps = maxSubSteps || 10;
  71785. timeSinceLastCalled = timeSinceLastCalled || 0;
  71786. if (timeSinceLastCalled === 0) {
  71787. this.internalStep(dt);
  71788. this.time += dt;
  71789. }
  71790. else {
  71791. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  71792. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  71793. var t0 = performance.now();
  71794. for (var i = 0; i !== internalSteps; i++) {
  71795. this.internalStep(dt);
  71796. if (performance.now() - t0 > dt * 1000) {
  71797. break;
  71798. }
  71799. }
  71800. this.time += timeSinceLastCalled;
  71801. var h = this.time % dt;
  71802. var h_div_dt = h / dt;
  71803. var interpvelo = step_tmp1;
  71804. var bodies = this.bodies;
  71805. for (var j = 0; j !== bodies.length; j++) {
  71806. var b = bodies[j];
  71807. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  71808. b.position.vsub(b.previousPosition, interpvelo);
  71809. interpvelo.scale(h_div_dt, interpvelo);
  71810. b.position.vadd(interpvelo, b.interpolatedPosition);
  71811. }
  71812. else {
  71813. b.interpolatedPosition.copy(b.position);
  71814. b.interpolatedQuaternion.copy(b.quaternion);
  71815. }
  71816. }
  71817. }
  71818. };
  71819. };
  71820. return CannonJSPlugin;
  71821. }());
  71822. BABYLON.CannonJSPlugin = CannonJSPlugin;
  71823. })(BABYLON || (BABYLON = {}));
  71824. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  71825. var BABYLON;
  71826. (function (BABYLON) {
  71827. var OimoJSPlugin = /** @class */ (function () {
  71828. function OimoJSPlugin(iterations) {
  71829. this.name = "OimoJSPlugin";
  71830. this._tmpImpostorsArray = [];
  71831. this._tmpPositionVector = BABYLON.Vector3.Zero();
  71832. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  71833. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  71834. this.world.worldscale(1);
  71835. this.world.clear();
  71836. //making sure no stats are calculated
  71837. this.world.isNoStat = true;
  71838. }
  71839. OimoJSPlugin.prototype.setGravity = function (gravity) {
  71840. this.world.gravity.copy(gravity);
  71841. };
  71842. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  71843. this.world.timeStep = timeStep;
  71844. };
  71845. OimoJSPlugin.prototype.getTimeStep = function () {
  71846. return this.world.timeStep;
  71847. };
  71848. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  71849. var _this = this;
  71850. impostors.forEach(function (impostor) {
  71851. impostor.beforeStep();
  71852. });
  71853. this.world.step();
  71854. impostors.forEach(function (impostor) {
  71855. impostor.afterStep();
  71856. //update the ordered impostors array
  71857. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  71858. });
  71859. //check for collisions
  71860. var contact = this.world.contacts;
  71861. while (contact !== null) {
  71862. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  71863. contact = contact.next;
  71864. continue;
  71865. }
  71866. //is this body colliding with any other? get the impostor
  71867. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  71868. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  71869. if (!mainImpostor || !collidingImpostor) {
  71870. contact = contact.next;
  71871. continue;
  71872. }
  71873. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  71874. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  71875. contact = contact.next;
  71876. }
  71877. };
  71878. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71879. var mass = impostor.physicsBody.massInfo.mass;
  71880. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  71881. };
  71882. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71883. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  71884. this.applyImpulse(impostor, force, contactPoint);
  71885. };
  71886. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71887. var _this = this;
  71888. //parent-child relationship. Does this impostor has a parent impostor?
  71889. if (impostor.parent) {
  71890. if (impostor.physicsBody) {
  71891. this.removePhysicsBody(impostor);
  71892. //TODO is that needed?
  71893. impostor.forceUpdate();
  71894. }
  71895. return;
  71896. }
  71897. if (impostor.isBodyInitRequired()) {
  71898. var bodyConfig = {
  71899. name: impostor.uniqueId,
  71900. //Oimo must have mass, also for static objects.
  71901. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  71902. size: [],
  71903. type: [],
  71904. pos: [],
  71905. rot: [],
  71906. move: impostor.getParam("mass") !== 0,
  71907. //Supporting older versions of Oimo
  71908. world: this.world
  71909. };
  71910. var impostors = [impostor];
  71911. var addToArray = function (parent) {
  71912. if (!parent.getChildMeshes)
  71913. return;
  71914. parent.getChildMeshes().forEach(function (m) {
  71915. if (m.physicsImpostor) {
  71916. impostors.push(m.physicsImpostor);
  71917. //m.physicsImpostor._init();
  71918. }
  71919. });
  71920. };
  71921. addToArray(impostor.object);
  71922. var checkWithEpsilon_1 = function (value) {
  71923. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  71924. };
  71925. impostors.forEach(function (i) {
  71926. if (!impostor.object.rotationQuaternion) {
  71927. return;
  71928. }
  71929. //get the correct bounding box
  71930. var oldQuaternion = i.object.rotationQuaternion;
  71931. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  71932. x: impostor.object.rotationQuaternion.x,
  71933. y: impostor.object.rotationQuaternion.y,
  71934. z: impostor.object.rotationQuaternion.z,
  71935. s: impostor.object.rotationQuaternion.w
  71936. });
  71937. var extendSize = i.getObjectExtendSize();
  71938. if (i === impostor) {
  71939. var center = impostor.getObjectCenter();
  71940. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  71941. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  71942. //Can also use Array.prototype.push.apply
  71943. bodyConfig.pos.push(center.x);
  71944. bodyConfig.pos.push(center.y);
  71945. bodyConfig.pos.push(center.z);
  71946. //tmp solution
  71947. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71948. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71949. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  71950. }
  71951. else {
  71952. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  71953. bodyConfig.pos.push(localPosition.x);
  71954. bodyConfig.pos.push(localPosition.y);
  71955. bodyConfig.pos.push(localPosition.z);
  71956. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  71957. bodyConfig.rot.push(0);
  71958. bodyConfig.rot.push(0);
  71959. bodyConfig.rot.push(0);
  71960. }
  71961. // register mesh
  71962. switch (i.type) {
  71963. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71964. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  71965. case BABYLON.PhysicsImpostor.SphereImpostor:
  71966. var radiusX = extendSize.x;
  71967. var radiusY = extendSize.y;
  71968. var radiusZ = extendSize.z;
  71969. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  71970. bodyConfig.type.push('sphere');
  71971. //due to the way oimo works with compounds, add 3 times
  71972. bodyConfig.size.push(size);
  71973. bodyConfig.size.push(size);
  71974. bodyConfig.size.push(size);
  71975. break;
  71976. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71977. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  71978. var sizeY = checkWithEpsilon_1(extendSize.y);
  71979. bodyConfig.type.push('cylinder');
  71980. bodyConfig.size.push(sizeX);
  71981. bodyConfig.size.push(sizeY);
  71982. //due to the way oimo works with compounds, add one more value.
  71983. bodyConfig.size.push(sizeY);
  71984. break;
  71985. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71986. case BABYLON.PhysicsImpostor.BoxImpostor:
  71987. default:
  71988. var sizeX = checkWithEpsilon_1(extendSize.x);
  71989. var sizeY = checkWithEpsilon_1(extendSize.y);
  71990. var sizeZ = checkWithEpsilon_1(extendSize.z);
  71991. bodyConfig.type.push('box');
  71992. bodyConfig.size.push(sizeX);
  71993. bodyConfig.size.push(sizeY);
  71994. bodyConfig.size.push(sizeZ);
  71995. break;
  71996. }
  71997. //actually not needed, but hey...
  71998. i.object.rotationQuaternion = oldQuaternion;
  71999. });
  72000. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  72001. }
  72002. else {
  72003. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  72004. }
  72005. impostor.setDeltaPosition(this._tmpPositionVector);
  72006. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  72007. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  72008. };
  72009. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72010. //impostor.physicsBody.dispose();
  72011. //Same as : (older oimo versions)
  72012. this.world.removeRigidBody(impostor.physicsBody);
  72013. };
  72014. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72015. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72016. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72017. if (!mainBody || !connectedBody) {
  72018. return;
  72019. }
  72020. var jointData = impostorJoint.joint.jointData;
  72021. var options = jointData.nativeParams || {};
  72022. var type;
  72023. var nativeJointData = {
  72024. body1: mainBody,
  72025. body2: connectedBody,
  72026. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  72027. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  72028. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  72029. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  72030. min: options.min,
  72031. max: options.max,
  72032. collision: options.collision || jointData.collision,
  72033. spring: options.spring,
  72034. //supporting older version of Oimo
  72035. world: this.world
  72036. };
  72037. switch (impostorJoint.joint.type) {
  72038. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72039. type = "jointBall";
  72040. break;
  72041. case BABYLON.PhysicsJoint.SpringJoint:
  72042. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  72043. var springData = jointData;
  72044. nativeJointData.min = springData.length || nativeJointData.min;
  72045. //Max should also be set, just make sure it is at least min
  72046. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  72047. case BABYLON.PhysicsJoint.DistanceJoint:
  72048. type = "jointDistance";
  72049. nativeJointData.max = jointData.maxDistance;
  72050. break;
  72051. case BABYLON.PhysicsJoint.PrismaticJoint:
  72052. type = "jointPrisme";
  72053. break;
  72054. case BABYLON.PhysicsJoint.SliderJoint:
  72055. type = "jointSlide";
  72056. break;
  72057. case BABYLON.PhysicsJoint.WheelJoint:
  72058. type = "jointWheel";
  72059. break;
  72060. case BABYLON.PhysicsJoint.HingeJoint:
  72061. default:
  72062. type = "jointHinge";
  72063. break;
  72064. }
  72065. nativeJointData.type = type;
  72066. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  72067. };
  72068. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72069. //Bug in Oimo prevents us from disposing a joint in the playground
  72070. //joint.joint.physicsJoint.dispose();
  72071. //So we will bruteforce it!
  72072. try {
  72073. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  72074. }
  72075. catch (e) {
  72076. BABYLON.Tools.Warn(e);
  72077. }
  72078. };
  72079. OimoJSPlugin.prototype.isSupported = function () {
  72080. return this.BJSOIMO !== undefined;
  72081. };
  72082. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72083. if (!impostor.physicsBody.sleeping) {
  72084. //TODO check that
  72085. if (impostor.physicsBody.shapes.next) {
  72086. var parentShape = this._getLastShape(impostor.physicsBody);
  72087. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  72088. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  72089. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  72090. }
  72091. else {
  72092. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  72093. }
  72094. if (impostor.object.rotationQuaternion) {
  72095. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  72096. impostor.object.rotationQuaternion.normalize();
  72097. }
  72098. }
  72099. };
  72100. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72101. var body = impostor.physicsBody;
  72102. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  72103. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  72104. body.syncShapes();
  72105. body.awake();
  72106. };
  72107. OimoJSPlugin.prototype._getLastShape = function (body) {
  72108. var lastShape = body.shapes;
  72109. while (lastShape.next) {
  72110. lastShape = lastShape.next;
  72111. }
  72112. return lastShape;
  72113. };
  72114. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72115. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  72116. };
  72117. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72118. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  72119. };
  72120. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72121. var v = impostor.physicsBody.linearVelocity;
  72122. if (!v) {
  72123. return null;
  72124. }
  72125. return new BABYLON.Vector3(v.x, v.y, v.z);
  72126. };
  72127. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72128. var v = impostor.physicsBody.angularVelocity;
  72129. if (!v) {
  72130. return null;
  72131. }
  72132. return new BABYLON.Vector3(v.x, v.y, v.z);
  72133. };
  72134. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72135. var staticBody = mass === 0;
  72136. //this will actually set the body's density and not its mass.
  72137. //But this is how oimo treats the mass variable.
  72138. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  72139. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  72140. };
  72141. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  72142. return impostor.physicsBody.shapes.density;
  72143. };
  72144. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  72145. return impostor.physicsBody.shapes.friction;
  72146. };
  72147. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72148. impostor.physicsBody.shapes.friction = friction;
  72149. };
  72150. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72151. return impostor.physicsBody.shapes.restitution;
  72152. };
  72153. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72154. impostor.physicsBody.shapes.restitution = restitution;
  72155. };
  72156. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  72157. impostor.physicsBody.sleep();
  72158. };
  72159. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  72160. impostor.physicsBody.awake();
  72161. };
  72162. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72163. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  72164. if (minDistance !== void 0) {
  72165. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  72166. }
  72167. };
  72168. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72169. //TODO separate rotational and transational motors.
  72170. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72171. if (motor) {
  72172. motor.setMotor(speed, maxForce);
  72173. }
  72174. };
  72175. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  72176. //TODO separate rotational and transational motors.
  72177. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72178. if (motor) {
  72179. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  72180. }
  72181. };
  72182. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72183. var body = impostor.physicsBody;
  72184. mesh.position.x = body.position.x;
  72185. mesh.position.y = body.position.y;
  72186. mesh.position.z = body.position.z;
  72187. if (mesh.rotationQuaternion) {
  72188. mesh.rotationQuaternion.x = body.orientation.x;
  72189. mesh.rotationQuaternion.y = body.orientation.y;
  72190. mesh.rotationQuaternion.z = body.orientation.z;
  72191. mesh.rotationQuaternion.w = body.orientation.s;
  72192. }
  72193. };
  72194. OimoJSPlugin.prototype.getRadius = function (impostor) {
  72195. return impostor.physicsBody.shapes.radius;
  72196. };
  72197. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72198. var shape = impostor.physicsBody.shapes;
  72199. result.x = shape.halfWidth * 2;
  72200. result.y = shape.halfHeight * 2;
  72201. result.z = shape.halfDepth * 2;
  72202. };
  72203. OimoJSPlugin.prototype.dispose = function () {
  72204. this.world.clear();
  72205. };
  72206. return OimoJSPlugin;
  72207. }());
  72208. BABYLON.OimoJSPlugin = OimoJSPlugin;
  72209. })(BABYLON || (BABYLON = {}));
  72210. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  72211. var BABYLON;
  72212. (function (BABYLON) {
  72213. /*
  72214. * Based on jsTGALoader - Javascript loader for TGA file
  72215. * By Vincent Thibault
  72216. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  72217. */
  72218. var TGATools = /** @class */ (function () {
  72219. function TGATools() {
  72220. }
  72221. TGATools.GetTGAHeader = function (data) {
  72222. var offset = 0;
  72223. var header = {
  72224. id_length: data[offset++],
  72225. colormap_type: data[offset++],
  72226. image_type: data[offset++],
  72227. colormap_index: data[offset++] | data[offset++] << 8,
  72228. colormap_length: data[offset++] | data[offset++] << 8,
  72229. colormap_size: data[offset++],
  72230. origin: [
  72231. data[offset++] | data[offset++] << 8,
  72232. data[offset++] | data[offset++] << 8
  72233. ],
  72234. width: data[offset++] | data[offset++] << 8,
  72235. height: data[offset++] | data[offset++] << 8,
  72236. pixel_size: data[offset++],
  72237. flags: data[offset++]
  72238. };
  72239. return header;
  72240. };
  72241. TGATools.UploadContent = function (gl, data) {
  72242. // Not enough data to contain header ?
  72243. if (data.length < 19) {
  72244. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  72245. return;
  72246. }
  72247. // Read Header
  72248. var offset = 18;
  72249. var header = TGATools.GetTGAHeader(data);
  72250. // Assume it's a valid Targa file.
  72251. if (header.id_length + offset > data.length) {
  72252. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  72253. return;
  72254. }
  72255. // Skip not needed data
  72256. offset += header.id_length;
  72257. var use_rle = false;
  72258. var use_pal = false;
  72259. var use_grey = false;
  72260. // Get some informations.
  72261. switch (header.image_type) {
  72262. case TGATools._TYPE_RLE_INDEXED:
  72263. use_rle = true;
  72264. case TGATools._TYPE_INDEXED:
  72265. use_pal = true;
  72266. break;
  72267. case TGATools._TYPE_RLE_RGB:
  72268. use_rle = true;
  72269. case TGATools._TYPE_RGB:
  72270. // use_rgb = true;
  72271. break;
  72272. case TGATools._TYPE_RLE_GREY:
  72273. use_rle = true;
  72274. case TGATools._TYPE_GREY:
  72275. use_grey = true;
  72276. break;
  72277. }
  72278. var pixel_data;
  72279. // var numAlphaBits = header.flags & 0xf;
  72280. var pixel_size = header.pixel_size >> 3;
  72281. var pixel_total = header.width * header.height * pixel_size;
  72282. // Read palettes
  72283. var palettes;
  72284. if (use_pal) {
  72285. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  72286. }
  72287. // Read LRE
  72288. if (use_rle) {
  72289. pixel_data = new Uint8Array(pixel_total);
  72290. var c, count, i;
  72291. var localOffset = 0;
  72292. var pixels = new Uint8Array(pixel_size);
  72293. while (offset < pixel_total && localOffset < pixel_total) {
  72294. c = data[offset++];
  72295. count = (c & 0x7f) + 1;
  72296. // RLE pixels
  72297. if (c & 0x80) {
  72298. // Bind pixel tmp array
  72299. for (i = 0; i < pixel_size; ++i) {
  72300. pixels[i] = data[offset++];
  72301. }
  72302. // Copy pixel array
  72303. for (i = 0; i < count; ++i) {
  72304. pixel_data.set(pixels, localOffset + i * pixel_size);
  72305. }
  72306. localOffset += pixel_size * count;
  72307. }
  72308. else {
  72309. count *= pixel_size;
  72310. for (i = 0; i < count; ++i) {
  72311. pixel_data[localOffset + i] = data[offset++];
  72312. }
  72313. localOffset += count;
  72314. }
  72315. }
  72316. }
  72317. else {
  72318. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  72319. }
  72320. // Load to texture
  72321. var x_start, y_start, x_step, y_step, y_end, x_end;
  72322. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  72323. default:
  72324. case TGATools._ORIGIN_UL:
  72325. x_start = 0;
  72326. x_step = 1;
  72327. x_end = header.width;
  72328. y_start = 0;
  72329. y_step = 1;
  72330. y_end = header.height;
  72331. break;
  72332. case TGATools._ORIGIN_BL:
  72333. x_start = 0;
  72334. x_step = 1;
  72335. x_end = header.width;
  72336. y_start = header.height - 1;
  72337. y_step = -1;
  72338. y_end = -1;
  72339. break;
  72340. case TGATools._ORIGIN_UR:
  72341. x_start = header.width - 1;
  72342. x_step = -1;
  72343. x_end = -1;
  72344. y_start = 0;
  72345. y_step = 1;
  72346. y_end = header.height;
  72347. break;
  72348. case TGATools._ORIGIN_BR:
  72349. x_start = header.width - 1;
  72350. x_step = -1;
  72351. x_end = -1;
  72352. y_start = header.height - 1;
  72353. y_step = -1;
  72354. y_end = -1;
  72355. break;
  72356. }
  72357. // Load the specify method
  72358. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  72359. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  72360. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  72361. };
  72362. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72363. var image = pixel_data, colormap = palettes;
  72364. var width = header.width, height = header.height;
  72365. var color, i = 0, x, y;
  72366. var imageData = new Uint8Array(width * height * 4);
  72367. for (y = y_start; y !== y_end; y += y_step) {
  72368. for (x = x_start; x !== x_end; x += x_step, i++) {
  72369. color = image[i];
  72370. imageData[(x + width * y) * 4 + 3] = 255;
  72371. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  72372. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  72373. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  72374. }
  72375. }
  72376. return imageData;
  72377. };
  72378. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72379. var image = pixel_data;
  72380. var width = header.width, height = header.height;
  72381. var color, i = 0, x, y;
  72382. var imageData = new Uint8Array(width * height * 4);
  72383. for (y = y_start; y !== y_end; y += y_step) {
  72384. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72385. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  72386. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  72387. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  72388. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  72389. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  72390. }
  72391. }
  72392. return imageData;
  72393. };
  72394. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72395. var image = pixel_data;
  72396. var width = header.width, height = header.height;
  72397. var i = 0, x, y;
  72398. var imageData = new Uint8Array(width * height * 4);
  72399. for (y = y_start; y !== y_end; y += y_step) {
  72400. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  72401. imageData[(x + width * y) * 4 + 3] = 255;
  72402. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72403. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72404. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72405. }
  72406. }
  72407. return imageData;
  72408. };
  72409. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72410. var image = pixel_data;
  72411. var width = header.width, height = header.height;
  72412. var i = 0, x, y;
  72413. var imageData = new Uint8Array(width * height * 4);
  72414. for (y = y_start; y !== y_end; y += y_step) {
  72415. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  72416. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72417. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72418. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72419. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  72420. }
  72421. }
  72422. return imageData;
  72423. };
  72424. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72425. var image = pixel_data;
  72426. var width = header.width, height = header.height;
  72427. var color, i = 0, x, y;
  72428. var imageData = new Uint8Array(width * height * 4);
  72429. for (y = y_start; y !== y_end; y += y_step) {
  72430. for (x = x_start; x !== x_end; x += x_step, i++) {
  72431. color = image[i];
  72432. imageData[(x + width * y) * 4 + 0] = color;
  72433. imageData[(x + width * y) * 4 + 1] = color;
  72434. imageData[(x + width * y) * 4 + 2] = color;
  72435. imageData[(x + width * y) * 4 + 3] = 255;
  72436. }
  72437. }
  72438. return imageData;
  72439. };
  72440. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72441. var image = pixel_data;
  72442. var width = header.width, height = header.height;
  72443. var i = 0, x, y;
  72444. var imageData = new Uint8Array(width * height * 4);
  72445. for (y = y_start; y !== y_end; y += y_step) {
  72446. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72447. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72448. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72449. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72450. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72451. }
  72452. }
  72453. return imageData;
  72454. };
  72455. //private static _TYPE_NO_DATA = 0;
  72456. TGATools._TYPE_INDEXED = 1;
  72457. TGATools._TYPE_RGB = 2;
  72458. TGATools._TYPE_GREY = 3;
  72459. TGATools._TYPE_RLE_INDEXED = 9;
  72460. TGATools._TYPE_RLE_RGB = 10;
  72461. TGATools._TYPE_RLE_GREY = 11;
  72462. TGATools._ORIGIN_MASK = 0x30;
  72463. TGATools._ORIGIN_SHIFT = 0x04;
  72464. TGATools._ORIGIN_BL = 0x00;
  72465. TGATools._ORIGIN_BR = 0x01;
  72466. TGATools._ORIGIN_UL = 0x02;
  72467. TGATools._ORIGIN_UR = 0x03;
  72468. return TGATools;
  72469. }());
  72470. BABYLON.TGATools = TGATools;
  72471. })(BABYLON || (BABYLON = {}));
  72472. //# sourceMappingURL=babylon.tga.js.map
  72473. var BABYLON;
  72474. (function (BABYLON) {
  72475. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72476. // All values and structures referenced from:
  72477. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72478. var DDS_MAGIC = 0x20534444;
  72479. var
  72480. //DDSD_CAPS = 0x1,
  72481. //DDSD_HEIGHT = 0x2,
  72482. //DDSD_WIDTH = 0x4,
  72483. //DDSD_PITCH = 0x8,
  72484. //DDSD_PIXELFORMAT = 0x1000,
  72485. DDSD_MIPMAPCOUNT = 0x20000;
  72486. //DDSD_LINEARSIZE = 0x80000,
  72487. //DDSD_DEPTH = 0x800000;
  72488. // var DDSCAPS_COMPLEX = 0x8,
  72489. // DDSCAPS_MIPMAP = 0x400000,
  72490. // DDSCAPS_TEXTURE = 0x1000;
  72491. var DDSCAPS2_CUBEMAP = 0x200;
  72492. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72493. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72494. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72495. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72496. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72497. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72498. // DDSCAPS2_VOLUME = 0x200000;
  72499. var
  72500. //DDPF_ALPHAPIXELS = 0x1,
  72501. //DDPF_ALPHA = 0x2,
  72502. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72503. //DDPF_YUV = 0x200,
  72504. DDPF_LUMINANCE = 0x20000;
  72505. function FourCCToInt32(value) {
  72506. return value.charCodeAt(0) +
  72507. (value.charCodeAt(1) << 8) +
  72508. (value.charCodeAt(2) << 16) +
  72509. (value.charCodeAt(3) << 24);
  72510. }
  72511. function Int32ToFourCC(value) {
  72512. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72513. }
  72514. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72515. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72516. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72517. var FOURCC_DX10 = FourCCToInt32("DX10");
  72518. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72519. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72520. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72521. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72522. var headerLengthInt = 31; // The header length in 32 bit ints
  72523. // Offsets into the header array
  72524. var off_magic = 0;
  72525. var off_size = 1;
  72526. var off_flags = 2;
  72527. var off_height = 3;
  72528. var off_width = 4;
  72529. var off_mipmapCount = 7;
  72530. var off_pfFlags = 20;
  72531. var off_pfFourCC = 21;
  72532. var off_RGBbpp = 22;
  72533. var off_RMask = 23;
  72534. var off_GMask = 24;
  72535. var off_BMask = 25;
  72536. var off_AMask = 26;
  72537. // var off_caps1 = 27;
  72538. var off_caps2 = 28;
  72539. // var off_caps3 = 29;
  72540. // var off_caps4 = 30;
  72541. var off_dxgiFormat = 32;
  72542. ;
  72543. var DDSTools = /** @class */ (function () {
  72544. function DDSTools() {
  72545. }
  72546. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72547. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72548. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72549. var mipmapCount = 1;
  72550. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72551. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72552. }
  72553. var fourCC = header[off_pfFourCC];
  72554. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72555. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72556. switch (fourCC) {
  72557. case FOURCC_D3DFMT_R16G16B16A16F:
  72558. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72559. break;
  72560. case FOURCC_D3DFMT_R32G32B32A32F:
  72561. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72562. break;
  72563. case FOURCC_DX10:
  72564. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72565. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72566. break;
  72567. }
  72568. }
  72569. return {
  72570. width: header[off_width],
  72571. height: header[off_height],
  72572. mipmapCount: mipmapCount,
  72573. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72574. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72575. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72576. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72577. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72578. dxgiFormat: dxgiFormat,
  72579. textureType: textureType
  72580. };
  72581. };
  72582. DDSTools._ToHalfFloat = function (value) {
  72583. if (!DDSTools._FloatView) {
  72584. DDSTools._FloatView = new Float32Array(1);
  72585. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72586. }
  72587. DDSTools._FloatView[0] = value;
  72588. var x = DDSTools._Int32View[0];
  72589. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72590. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72591. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72592. /* If zero, or denormal, or exponent underflows too much for a denormal
  72593. * half, return signed zero. */
  72594. if (e < 103) {
  72595. return bits;
  72596. }
  72597. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72598. if (e > 142) {
  72599. bits |= 0x7c00;
  72600. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72601. * not Inf, so make sure we set one mantissa bit too. */
  72602. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72603. return bits;
  72604. }
  72605. /* If exponent underflows but not too much, return a denormal */
  72606. if (e < 113) {
  72607. m |= 0x0800;
  72608. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72609. * to 1, which is OK. */
  72610. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72611. return bits;
  72612. }
  72613. bits |= ((e - 112) << 10) | (m >> 1);
  72614. bits += m & 1;
  72615. return bits;
  72616. };
  72617. DDSTools._FromHalfFloat = function (value) {
  72618. var s = (value & 0x8000) >> 15;
  72619. var e = (value & 0x7C00) >> 10;
  72620. var f = value & 0x03FF;
  72621. if (e === 0) {
  72622. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72623. }
  72624. else if (e == 0x1F) {
  72625. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72626. }
  72627. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72628. };
  72629. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72630. var destArray = new Float32Array(dataLength);
  72631. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72632. var index = 0;
  72633. for (var y = 0; y < height; y++) {
  72634. for (var x = 0; x < width; x++) {
  72635. var srcPos = (x + y * width) * 4;
  72636. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72637. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72638. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72639. if (DDSTools.StoreLODInAlphaChannel) {
  72640. destArray[index + 3] = lod;
  72641. }
  72642. else {
  72643. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72644. }
  72645. index += 4;
  72646. }
  72647. }
  72648. return destArray;
  72649. };
  72650. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72651. if (DDSTools.StoreLODInAlphaChannel) {
  72652. var destArray = new Uint16Array(dataLength);
  72653. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72654. var index = 0;
  72655. for (var y = 0; y < height; y++) {
  72656. for (var x = 0; x < width; x++) {
  72657. var srcPos = (x + y * width) * 4;
  72658. destArray[index] = srcData[srcPos];
  72659. destArray[index + 1] = srcData[srcPos + 1];
  72660. destArray[index + 2] = srcData[srcPos + 2];
  72661. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72662. index += 4;
  72663. }
  72664. }
  72665. return destArray;
  72666. }
  72667. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  72668. };
  72669. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72670. if (DDSTools.StoreLODInAlphaChannel) {
  72671. var destArray = new Float32Array(dataLength);
  72672. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72673. var index = 0;
  72674. for (var y = 0; y < height; y++) {
  72675. for (var x = 0; x < width; x++) {
  72676. var srcPos = (x + y * width) * 4;
  72677. destArray[index] = srcData[srcPos];
  72678. destArray[index + 1] = srcData[srcPos + 1];
  72679. destArray[index + 2] = srcData[srcPos + 2];
  72680. destArray[index + 3] = lod;
  72681. index += 4;
  72682. }
  72683. }
  72684. return destArray;
  72685. }
  72686. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  72687. };
  72688. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72689. var destArray = new Uint8Array(dataLength);
  72690. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72691. var index = 0;
  72692. for (var y = 0; y < height; y++) {
  72693. for (var x = 0; x < width; x++) {
  72694. var srcPos = (x + y * width) * 4;
  72695. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  72696. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  72697. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  72698. if (DDSTools.StoreLODInAlphaChannel) {
  72699. destArray[index + 3] = lod;
  72700. }
  72701. else {
  72702. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  72703. }
  72704. index += 4;
  72705. }
  72706. }
  72707. return destArray;
  72708. };
  72709. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72710. var destArray = new Uint8Array(dataLength);
  72711. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72712. var index = 0;
  72713. for (var y = 0; y < height; y++) {
  72714. for (var x = 0; x < width; x++) {
  72715. var srcPos = (x + y * width) * 4;
  72716. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  72717. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  72718. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  72719. if (DDSTools.StoreLODInAlphaChannel) {
  72720. destArray[index + 3] = lod;
  72721. }
  72722. else {
  72723. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  72724. }
  72725. index += 4;
  72726. }
  72727. }
  72728. return destArray;
  72729. };
  72730. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  72731. var byteArray = new Uint8Array(dataLength);
  72732. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72733. var index = 0;
  72734. for (var y = 0; y < height; y++) {
  72735. for (var x = 0; x < width; x++) {
  72736. var srcPos = (x + y * width) * 4;
  72737. byteArray[index] = srcData[srcPos + rOffset];
  72738. byteArray[index + 1] = srcData[srcPos + gOffset];
  72739. byteArray[index + 2] = srcData[srcPos + bOffset];
  72740. byteArray[index + 3] = srcData[srcPos + aOffset];
  72741. index += 4;
  72742. }
  72743. }
  72744. return byteArray;
  72745. };
  72746. DDSTools._ExtractLongWordOrder = function (value) {
  72747. if (value === 0 || value === 255 || value === -16777216) {
  72748. return 0;
  72749. }
  72750. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  72751. };
  72752. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  72753. var byteArray = new Uint8Array(dataLength);
  72754. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72755. var index = 0;
  72756. for (var y = 0; y < height; y++) {
  72757. for (var x = 0; x < width; x++) {
  72758. var srcPos = (x + y * width) * 3;
  72759. byteArray[index] = srcData[srcPos + rOffset];
  72760. byteArray[index + 1] = srcData[srcPos + gOffset];
  72761. byteArray[index + 2] = srcData[srcPos + bOffset];
  72762. index += 3;
  72763. }
  72764. }
  72765. return byteArray;
  72766. };
  72767. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  72768. var byteArray = new Uint8Array(dataLength);
  72769. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72770. var index = 0;
  72771. for (var y = 0; y < height; y++) {
  72772. for (var x = 0; x < width; x++) {
  72773. var srcPos = (x + y * width);
  72774. byteArray[index] = srcData[srcPos];
  72775. index++;
  72776. }
  72777. }
  72778. return byteArray;
  72779. };
  72780. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  72781. if (lodIndex === void 0) { lodIndex = -1; }
  72782. var ext = engine.getCaps().s3tc;
  72783. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72784. var fourCC, width, height, dataLength = 0, dataOffset;
  72785. var byteArray, mipmapCount, mip;
  72786. var internalFormat = 0;
  72787. var format = 0;
  72788. var blockBytes = 1;
  72789. if (header[off_magic] !== DDS_MAGIC) {
  72790. BABYLON.Tools.Error("Invalid magic number in DDS header");
  72791. return;
  72792. }
  72793. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  72794. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  72795. return;
  72796. }
  72797. if (info.isCompressed && !ext) {
  72798. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  72799. return;
  72800. }
  72801. var bpp = header[off_RGBbpp];
  72802. dataOffset = header[off_size] + 4;
  72803. var computeFormats = false;
  72804. if (info.isFourCC) {
  72805. fourCC = header[off_pfFourCC];
  72806. switch (fourCC) {
  72807. case FOURCC_DXT1:
  72808. blockBytes = 8;
  72809. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  72810. break;
  72811. case FOURCC_DXT3:
  72812. blockBytes = 16;
  72813. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  72814. break;
  72815. case FOURCC_DXT5:
  72816. blockBytes = 16;
  72817. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  72818. break;
  72819. case FOURCC_D3DFMT_R16G16B16A16F:
  72820. computeFormats = true;
  72821. break;
  72822. case FOURCC_D3DFMT_R32G32B32A32F:
  72823. computeFormats = true;
  72824. break;
  72825. case FOURCC_DX10:
  72826. // There is an additionnal header so dataOffset need to be changed
  72827. dataOffset += 5 * 4; // 5 uints
  72828. var supported = false;
  72829. switch (info.dxgiFormat) {
  72830. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  72831. computeFormats = true;
  72832. supported = true;
  72833. break;
  72834. case DXGI_FORMAT_B8G8R8X8_UNORM:
  72835. info.isRGB = true;
  72836. info.isFourCC = false;
  72837. bpp = 32;
  72838. supported = true;
  72839. break;
  72840. }
  72841. if (supported) {
  72842. break;
  72843. }
  72844. default:
  72845. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  72846. return;
  72847. }
  72848. }
  72849. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  72850. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  72851. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  72852. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  72853. if (computeFormats) {
  72854. format = engine._getWebGLTextureType(info.textureType);
  72855. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72856. }
  72857. mipmapCount = 1;
  72858. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  72859. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72860. }
  72861. for (var face = 0; face < faces; face++) {
  72862. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  72863. width = header[off_width];
  72864. height = header[off_height];
  72865. for (mip = 0; mip < mipmapCount; ++mip) {
  72866. if (lodIndex === -1 || lodIndex === mip) {
  72867. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  72868. var i = (lodIndex === -1) ? mip : 0;
  72869. if (!info.isCompressed && info.isFourCC) {
  72870. dataLength = width * height * 4;
  72871. var floatArray = null;
  72872. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  72873. if (bpp === 128) {
  72874. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72875. }
  72876. else if (bpp === 64) {
  72877. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72878. }
  72879. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72880. format = engine._getWebGLTextureType(info.textureType);
  72881. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72882. }
  72883. else {
  72884. if (bpp === 128) {
  72885. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72886. }
  72887. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  72888. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72889. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72890. format = engine._getWebGLTextureType(info.textureType);
  72891. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72892. }
  72893. else {
  72894. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72895. }
  72896. }
  72897. if (floatArray) {
  72898. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  72899. }
  72900. }
  72901. else if (info.isRGB) {
  72902. if (bpp === 24) {
  72903. dataLength = width * height * 3;
  72904. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  72905. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  72906. }
  72907. else {
  72908. dataLength = width * height * 4;
  72909. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  72910. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  72911. }
  72912. }
  72913. else if (info.isLuminance) {
  72914. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  72915. var unpaddedRowSize = width;
  72916. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  72917. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  72918. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  72919. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  72920. }
  72921. else {
  72922. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  72923. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  72924. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  72925. }
  72926. }
  72927. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  72928. width *= 0.5;
  72929. height *= 0.5;
  72930. width = Math.max(1.0, width);
  72931. height = Math.max(1.0, height);
  72932. }
  72933. if (currentFace !== undefined) {
  72934. // Loading a single face
  72935. break;
  72936. }
  72937. }
  72938. };
  72939. DDSTools.StoreLODInAlphaChannel = false;
  72940. return DDSTools;
  72941. }());
  72942. BABYLON.DDSTools = DDSTools;
  72943. })(BABYLON || (BABYLON = {}));
  72944. //# sourceMappingURL=babylon.dds.js.map
  72945. var BABYLON;
  72946. (function (BABYLON) {
  72947. /**
  72948. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  72949. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  72950. */
  72951. var KhronosTextureContainer = /** @class */ (function () {
  72952. /**
  72953. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  72954. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  72955. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  72956. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  72957. */
  72958. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  72959. this.arrayBuffer = arrayBuffer;
  72960. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  72961. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  72962. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  72963. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  72964. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  72965. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  72966. BABYLON.Tools.Error("texture missing KTX identifier");
  72967. return;
  72968. }
  72969. // load the reset of the header in native 32 bit int
  72970. var header = new Int32Array(this.arrayBuffer, 12, 13);
  72971. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  72972. var oppositeEndianess = header[0] === 0x01020304;
  72973. // read all the header elements in order they exist in the file, without modification (sans endainness)
  72974. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  72975. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  72976. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  72977. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  72978. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  72979. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  72980. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  72981. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  72982. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  72983. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  72984. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  72985. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  72986. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  72987. if (this.glType !== 0) {
  72988. BABYLON.Tools.Error("only compressed formats currently supported");
  72989. return;
  72990. }
  72991. else {
  72992. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  72993. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  72994. }
  72995. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  72996. BABYLON.Tools.Error("only 2D textures currently supported");
  72997. return;
  72998. }
  72999. if (this.numberOfArrayElements !== 0) {
  73000. BABYLON.Tools.Error("texture arrays not currently supported");
  73001. return;
  73002. }
  73003. if (this.numberOfFaces !== facesExpected) {
  73004. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  73005. return;
  73006. }
  73007. // we now have a completely validated file, so could use existence of loadType as success
  73008. // would need to make this more elaborate & adjust checks above to support more than one load type
  73009. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  73010. }
  73011. // not as fast hardware based, but will probably never need to use
  73012. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  73013. return ((val & 0xFF) << 24)
  73014. | ((val & 0xFF00) << 8)
  73015. | ((val >> 8) & 0xFF00)
  73016. | ((val >> 24) & 0xFF);
  73017. };
  73018. /**
  73019. * It is assumed that the texture has already been created & is currently bound
  73020. */
  73021. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  73022. switch (this.loadType) {
  73023. case KhronosTextureContainer.COMPRESSED_2D:
  73024. this._upload2DCompressedLevels(gl, loadMipmaps);
  73025. break;
  73026. case KhronosTextureContainer.TEX_2D:
  73027. case KhronosTextureContainer.COMPRESSED_3D:
  73028. case KhronosTextureContainer.TEX_3D:
  73029. }
  73030. };
  73031. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  73032. // initialize width & height for level 1
  73033. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  73034. var width = this.pixelWidth;
  73035. var height = this.pixelHeight;
  73036. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  73037. for (var level = 0; level < mipmapCount; level++) {
  73038. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  73039. for (var face = 0; face < this.numberOfFaces; face++) {
  73040. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  73041. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  73042. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  73043. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  73044. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  73045. }
  73046. width = Math.max(1.0, width * 0.5);
  73047. height = Math.max(1.0, height * 0.5);
  73048. }
  73049. };
  73050. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  73051. // load types
  73052. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  73053. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  73054. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  73055. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  73056. return KhronosTextureContainer;
  73057. }());
  73058. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  73059. })(BABYLON || (BABYLON = {}));
  73060. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  73061. var BABYLON;
  73062. (function (BABYLON) {
  73063. var Debug = /** @class */ (function () {
  73064. function Debug() {
  73065. }
  73066. Debug.AxesViewer = /** @class */ (function () {
  73067. function AxesViewer(scene, scaleLines) {
  73068. if (scaleLines === void 0) { scaleLines = 1; }
  73069. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73070. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73071. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73072. this.scaleLines = 1;
  73073. this.scaleLines = scaleLines;
  73074. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  73075. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  73076. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  73077. this._xmesh.renderingGroupId = 2;
  73078. this._ymesh.renderingGroupId = 2;
  73079. this._zmesh.renderingGroupId = 2;
  73080. this._xmesh.material.checkReadyOnlyOnce = true;
  73081. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  73082. this._ymesh.material.checkReadyOnlyOnce = true;
  73083. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  73084. this._zmesh.material.checkReadyOnlyOnce = true;
  73085. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  73086. this.scene = scene;
  73087. }
  73088. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  73089. var scaleLines = this.scaleLines;
  73090. if (this._xmesh) {
  73091. this._xmesh.position.copyFrom(position);
  73092. }
  73093. if (this._ymesh) {
  73094. this._ymesh.position.copyFrom(position);
  73095. }
  73096. if (this._zmesh) {
  73097. this._zmesh.position.copyFrom(position);
  73098. }
  73099. var point2 = this._xline[1];
  73100. point2.x = xaxis.x * scaleLines;
  73101. point2.y = xaxis.y * scaleLines;
  73102. point2.z = xaxis.z * scaleLines;
  73103. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  73104. point2 = this._yline[1];
  73105. point2.x = yaxis.x * scaleLines;
  73106. point2.y = yaxis.y * scaleLines;
  73107. point2.z = yaxis.z * scaleLines;
  73108. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  73109. point2 = this._zline[1];
  73110. point2.x = zaxis.x * scaleLines;
  73111. point2.y = zaxis.y * scaleLines;
  73112. point2.z = zaxis.z * scaleLines;
  73113. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  73114. };
  73115. AxesViewer.prototype.dispose = function () {
  73116. if (this._xmesh) {
  73117. this._xmesh.dispose();
  73118. }
  73119. if (this._ymesh) {
  73120. this._ymesh.dispose();
  73121. }
  73122. if (this._zmesh) {
  73123. this._zmesh.dispose();
  73124. }
  73125. this._xmesh = null;
  73126. this._ymesh = null;
  73127. this._zmesh = null;
  73128. this.scene = null;
  73129. };
  73130. return AxesViewer;
  73131. }());
  73132. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  73133. __extends(BoneAxesViewer, _super);
  73134. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  73135. if (scaleLines === void 0) { scaleLines = 1; }
  73136. var _this = _super.call(this, scene, scaleLines) || this;
  73137. _this.pos = BABYLON.Vector3.Zero();
  73138. _this.xaxis = BABYLON.Vector3.Zero();
  73139. _this.yaxis = BABYLON.Vector3.Zero();
  73140. _this.zaxis = BABYLON.Vector3.Zero();
  73141. _this.mesh = mesh;
  73142. _this.bone = bone;
  73143. return _this;
  73144. }
  73145. BoneAxesViewer.prototype.update = function () {
  73146. if (!this.mesh || !this.bone) {
  73147. return;
  73148. }
  73149. var bone = this.bone;
  73150. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  73151. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  73152. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  73153. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  73154. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  73155. };
  73156. BoneAxesViewer.prototype.dispose = function () {
  73157. if (this.mesh) {
  73158. this.mesh = null;
  73159. this.bone = null;
  73160. _super.prototype.dispose.call(this);
  73161. }
  73162. };
  73163. return BoneAxesViewer;
  73164. }(Debug.AxesViewer));
  73165. Debug.PhysicsViewer = /** @class */ (function () {
  73166. function PhysicsViewer(scene) {
  73167. this._impostors = [];
  73168. this._meshes = [];
  73169. this._numMeshes = 0;
  73170. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73171. var physicEngine = this._scene.getPhysicsEngine();
  73172. if (physicEngine) {
  73173. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  73174. }
  73175. }
  73176. PhysicsViewer.prototype._updateDebugMeshes = function () {
  73177. var plugin = this._physicsEnginePlugin;
  73178. for (var i = 0; i < this._numMeshes; i++) {
  73179. var impostor = this._impostors[i];
  73180. if (!impostor) {
  73181. continue;
  73182. }
  73183. if (impostor.isDisposed) {
  73184. this.hideImpostor(this._impostors[i--]);
  73185. }
  73186. else {
  73187. var mesh = this._meshes[i];
  73188. if (mesh && plugin) {
  73189. plugin.syncMeshWithImpostor(mesh, impostor);
  73190. }
  73191. }
  73192. }
  73193. };
  73194. PhysicsViewer.prototype.showImpostor = function (impostor) {
  73195. if (!this._scene) {
  73196. return;
  73197. }
  73198. for (var i = 0; i < this._numMeshes; i++) {
  73199. if (this._impostors[i] == impostor) {
  73200. return;
  73201. }
  73202. }
  73203. var debugMesh = this._getDebugMesh(impostor, this._scene);
  73204. if (debugMesh) {
  73205. this._impostors[this._numMeshes] = impostor;
  73206. this._meshes[this._numMeshes] = debugMesh;
  73207. if (this._numMeshes === 0) {
  73208. this._renderFunction = this._updateDebugMeshes.bind(this);
  73209. this._scene.registerBeforeRender(this._renderFunction);
  73210. }
  73211. this._numMeshes++;
  73212. }
  73213. };
  73214. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  73215. if (!impostor || !this._scene) {
  73216. return;
  73217. }
  73218. var removed = false;
  73219. for (var i = 0; i < this._numMeshes; i++) {
  73220. if (this._impostors[i] == impostor) {
  73221. var mesh = this._meshes[i];
  73222. if (!mesh) {
  73223. continue;
  73224. }
  73225. this._scene.removeMesh(mesh);
  73226. mesh.dispose();
  73227. this._numMeshes--;
  73228. if (this._numMeshes > 0) {
  73229. this._meshes[i] = this._meshes[this._numMeshes];
  73230. this._impostors[i] = this._impostors[this._numMeshes];
  73231. this._meshes[this._numMeshes] = null;
  73232. this._impostors[this._numMeshes] = null;
  73233. }
  73234. else {
  73235. this._meshes[0] = null;
  73236. this._impostors[0] = null;
  73237. }
  73238. removed = true;
  73239. break;
  73240. }
  73241. }
  73242. if (removed && this._numMeshes === 0) {
  73243. this._scene.unregisterBeforeRender(this._renderFunction);
  73244. }
  73245. };
  73246. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  73247. if (!this._debugMaterial) {
  73248. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  73249. this._debugMaterial.wireframe = true;
  73250. }
  73251. return this._debugMaterial;
  73252. };
  73253. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  73254. if (!this._debugBoxMesh) {
  73255. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  73256. this._debugBoxMesh.renderingGroupId = 1;
  73257. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73258. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  73259. scene.removeMesh(this._debugBoxMesh);
  73260. }
  73261. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  73262. };
  73263. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  73264. if (!this._debugSphereMesh) {
  73265. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  73266. this._debugSphereMesh.renderingGroupId = 1;
  73267. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73268. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  73269. scene.removeMesh(this._debugSphereMesh);
  73270. }
  73271. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  73272. };
  73273. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  73274. var mesh = null;
  73275. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  73276. mesh = this._getDebugBoxMesh(scene);
  73277. impostor.getBoxSizeToRef(mesh.scaling);
  73278. }
  73279. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  73280. mesh = this._getDebugSphereMesh(scene);
  73281. var radius = impostor.getRadius();
  73282. mesh.scaling.x = radius * 2;
  73283. mesh.scaling.y = radius * 2;
  73284. mesh.scaling.z = radius * 2;
  73285. }
  73286. return mesh;
  73287. };
  73288. PhysicsViewer.prototype.dispose = function () {
  73289. for (var i = 0; i < this._numMeshes; i++) {
  73290. this.hideImpostor(this._impostors[i]);
  73291. }
  73292. if (this._debugBoxMesh) {
  73293. this._debugBoxMesh.dispose();
  73294. }
  73295. if (this._debugSphereMesh) {
  73296. this._debugSphereMesh.dispose();
  73297. }
  73298. if (this._debugMaterial) {
  73299. this._debugMaterial.dispose();
  73300. }
  73301. this._impostors.length = 0;
  73302. this._scene = null;
  73303. this._physicsEnginePlugin = null;
  73304. };
  73305. return PhysicsViewer;
  73306. }());
  73307. Debug.SkeletonViewer = /** @class */ (function () {
  73308. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  73309. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  73310. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  73311. this.skeleton = skeleton;
  73312. this.mesh = mesh;
  73313. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  73314. this.renderingGroupId = renderingGroupId;
  73315. this.color = BABYLON.Color3.White();
  73316. this._debugLines = new Array();
  73317. this._isEnabled = false;
  73318. this._scene = scene;
  73319. this.update();
  73320. this._renderFunction = this.update.bind(this);
  73321. }
  73322. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  73323. get: function () {
  73324. return this._isEnabled;
  73325. },
  73326. set: function (value) {
  73327. if (this._isEnabled === value) {
  73328. return;
  73329. }
  73330. this._isEnabled = value;
  73331. if (value) {
  73332. this._scene.registerBeforeRender(this._renderFunction);
  73333. }
  73334. else {
  73335. this._scene.unregisterBeforeRender(this._renderFunction);
  73336. }
  73337. },
  73338. enumerable: true,
  73339. configurable: true
  73340. });
  73341. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  73342. if (x === void 0) { x = 0; }
  73343. if (y === void 0) { y = 0; }
  73344. if (z === void 0) { z = 0; }
  73345. var tmat = BABYLON.Tmp.Matrix[0];
  73346. var parentBone = bone.getParent();
  73347. tmat.copyFrom(bone.getLocalMatrix());
  73348. if (x !== 0 || y !== 0 || z !== 0) {
  73349. var tmat2 = BABYLON.Tmp.Matrix[1];
  73350. BABYLON.Matrix.IdentityToRef(tmat2);
  73351. tmat2.m[12] = x;
  73352. tmat2.m[13] = y;
  73353. tmat2.m[14] = z;
  73354. tmat2.multiplyToRef(tmat, tmat);
  73355. }
  73356. if (parentBone) {
  73357. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  73358. }
  73359. tmat.multiplyToRef(meshMat, tmat);
  73360. position.x = tmat.m[12];
  73361. position.y = tmat.m[13];
  73362. position.z = tmat.m[14];
  73363. };
  73364. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  73365. var len = bones.length;
  73366. var meshPos = this.mesh.position;
  73367. for (var i = 0; i < len; i++) {
  73368. var bone = bones[i];
  73369. var points = this._debugLines[i];
  73370. if (!points) {
  73371. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73372. this._debugLines[i] = points;
  73373. }
  73374. this._getBonePosition(points[0], bone, meshMat);
  73375. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  73376. points[0].subtractInPlace(meshPos);
  73377. points[1].subtractInPlace(meshPos);
  73378. }
  73379. };
  73380. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  73381. var len = bones.length;
  73382. var boneNum = 0;
  73383. var meshPos = this.mesh.position;
  73384. for (var i = len - 1; i >= 0; i--) {
  73385. var childBone = bones[i];
  73386. var parentBone = childBone.getParent();
  73387. if (!parentBone) {
  73388. continue;
  73389. }
  73390. var points = this._debugLines[boneNum];
  73391. if (!points) {
  73392. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73393. this._debugLines[boneNum] = points;
  73394. }
  73395. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  73396. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  73397. points[0].subtractInPlace(meshPos);
  73398. points[1].subtractInPlace(meshPos);
  73399. boneNum++;
  73400. }
  73401. };
  73402. SkeletonViewer.prototype.update = function () {
  73403. if (this.autoUpdateBonesMatrices) {
  73404. this.skeleton.computeAbsoluteTransforms();
  73405. }
  73406. if (this.skeleton.bones[0].length === undefined) {
  73407. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73408. }
  73409. else {
  73410. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73411. }
  73412. if (!this._debugMesh) {
  73413. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  73414. this._debugMesh.renderingGroupId = this.renderingGroupId;
  73415. }
  73416. else {
  73417. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  73418. }
  73419. this._debugMesh.position.copyFrom(this.mesh.position);
  73420. this._debugMesh.color = this.color;
  73421. };
  73422. SkeletonViewer.prototype.dispose = function () {
  73423. if (this._debugMesh) {
  73424. this.isEnabled = false;
  73425. this._debugMesh.dispose();
  73426. this._debugMesh = null;
  73427. }
  73428. };
  73429. return SkeletonViewer;
  73430. }());
  73431. return Debug;
  73432. }());
  73433. BABYLON.Debug = Debug;
  73434. })(BABYLON || (BABYLON = {}));
  73435. //# sourceMappingURL=babylon.debugModules.js.map
  73436. var BABYLON;
  73437. (function (BABYLON) {
  73438. var RayHelper = /** @class */ (function () {
  73439. function RayHelper(ray) {
  73440. this.ray = ray;
  73441. }
  73442. RayHelper.CreateAndShow = function (ray, scene, color) {
  73443. var helper = new RayHelper(ray);
  73444. helper.show(scene, color);
  73445. return helper;
  73446. };
  73447. RayHelper.prototype.show = function (scene, color) {
  73448. if (!this._renderFunction && this.ray) {
  73449. var ray = this.ray;
  73450. this._renderFunction = this._render.bind(this);
  73451. this._scene = scene;
  73452. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73453. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73454. if (this._renderFunction) {
  73455. this._scene.registerBeforeRender(this._renderFunction);
  73456. }
  73457. }
  73458. if (color && this._renderLine) {
  73459. this._renderLine.color.copyFrom(color);
  73460. }
  73461. };
  73462. RayHelper.prototype.hide = function () {
  73463. if (this._renderFunction && this._scene) {
  73464. this._scene.unregisterBeforeRender(this._renderFunction);
  73465. this._scene = null;
  73466. this._renderFunction = null;
  73467. if (this._renderLine) {
  73468. this._renderLine.dispose();
  73469. this._renderLine = null;
  73470. }
  73471. this._renderPoints = [];
  73472. }
  73473. };
  73474. RayHelper.prototype._render = function () {
  73475. var ray = this.ray;
  73476. if (!ray) {
  73477. return;
  73478. }
  73479. var point = this._renderPoints[1];
  73480. var len = Math.min(ray.length, 1000000);
  73481. point.copyFrom(ray.direction);
  73482. point.scaleInPlace(len);
  73483. point.addInPlace(ray.origin);
  73484. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73485. };
  73486. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73487. this._attachedToMesh = mesh;
  73488. var ray = this.ray;
  73489. if (!ray) {
  73490. return;
  73491. }
  73492. if (!ray.direction) {
  73493. ray.direction = BABYLON.Vector3.Zero();
  73494. }
  73495. if (!ray.origin) {
  73496. ray.origin = BABYLON.Vector3.Zero();
  73497. }
  73498. if (length) {
  73499. ray.length = length;
  73500. }
  73501. if (!meshSpaceOrigin) {
  73502. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73503. }
  73504. if (!meshSpaceDirection) {
  73505. // -1 so that this will work with Mesh.lookAt
  73506. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73507. }
  73508. if (!this._meshSpaceDirection) {
  73509. this._meshSpaceDirection = meshSpaceDirection.clone();
  73510. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73511. }
  73512. else {
  73513. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73514. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73515. }
  73516. if (!this._updateToMeshFunction) {
  73517. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73518. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73519. }
  73520. this._updateToMesh();
  73521. };
  73522. RayHelper.prototype.detachFromMesh = function () {
  73523. if (this._attachedToMesh) {
  73524. if (this._updateToMeshFunction) {
  73525. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73526. }
  73527. this._attachedToMesh = null;
  73528. this._updateToMeshFunction = null;
  73529. }
  73530. };
  73531. RayHelper.prototype._updateToMesh = function () {
  73532. var ray = this.ray;
  73533. if (!this._attachedToMesh || !ray) {
  73534. return;
  73535. }
  73536. if (this._attachedToMesh._isDisposed) {
  73537. this.detachFromMesh();
  73538. return;
  73539. }
  73540. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73541. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73542. };
  73543. RayHelper.prototype.dispose = function () {
  73544. this.hide();
  73545. this.detachFromMesh();
  73546. this.ray = null;
  73547. };
  73548. return RayHelper;
  73549. }());
  73550. BABYLON.RayHelper = RayHelper;
  73551. })(BABYLON || (BABYLON = {}));
  73552. //# sourceMappingURL=babylon.rayHelper.js.map
  73553. var BABYLON;
  73554. (function (BABYLON) {
  73555. // load the inspector using require, if not present in the global namespace.
  73556. var DebugLayer = /** @class */ (function () {
  73557. function DebugLayer(scene) {
  73558. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73559. this._scene = scene;
  73560. // load inspector using require, if it doesn't exist on the global namespace.
  73561. }
  73562. /** Creates the inspector window. */
  73563. DebugLayer.prototype._createInspector = function (config) {
  73564. if (config === void 0) { config = {}; }
  73565. var popup = config.popup || false;
  73566. var initialTab = config.initialTab || 0;
  73567. var parentElement = config.parentElement || null;
  73568. if (!this._inspector) {
  73569. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73570. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73571. } // else nothing to do,; instance is already existing
  73572. };
  73573. DebugLayer.prototype.isVisible = function () {
  73574. if (!this._inspector) {
  73575. return false;
  73576. }
  73577. return true;
  73578. };
  73579. DebugLayer.prototype.hide = function () {
  73580. if (this._inspector) {
  73581. try {
  73582. this._inspector.dispose();
  73583. }
  73584. catch (e) {
  73585. // If the inspector has been removed directly from the inspector tool
  73586. }
  73587. this._inspector = null;
  73588. }
  73589. };
  73590. DebugLayer.prototype.show = function (config) {
  73591. if (config === void 0) { config = {}; }
  73592. if (typeof this.BJSINSPECTOR == 'undefined') {
  73593. // Load inspector and add it to the DOM
  73594. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73595. }
  73596. else {
  73597. // Otherwise creates the inspector
  73598. this._createInspector(config);
  73599. }
  73600. };
  73601. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73602. return DebugLayer;
  73603. }());
  73604. BABYLON.DebugLayer = DebugLayer;
  73605. })(BABYLON || (BABYLON = {}));
  73606. //# sourceMappingURL=babylon.debugLayer.js.map
  73607. var BABYLON;
  73608. (function (BABYLON) {
  73609. var BoundingBoxRenderer = /** @class */ (function () {
  73610. function BoundingBoxRenderer(scene) {
  73611. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73612. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73613. this.showBackLines = true;
  73614. this.renderList = new BABYLON.SmartArray(32);
  73615. this._vertexBuffers = {};
  73616. this._scene = scene;
  73617. }
  73618. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73619. if (this._colorShader) {
  73620. return;
  73621. }
  73622. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73623. attributes: [BABYLON.VertexBuffer.PositionKind],
  73624. uniforms: ["world", "viewProjection", "color"]
  73625. });
  73626. var engine = this._scene.getEngine();
  73627. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73628. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73629. this._createIndexBuffer();
  73630. };
  73631. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73632. var engine = this._scene.getEngine();
  73633. 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]);
  73634. };
  73635. BoundingBoxRenderer.prototype._rebuild = function () {
  73636. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73637. if (vb) {
  73638. vb._rebuild();
  73639. }
  73640. this._createIndexBuffer();
  73641. };
  73642. BoundingBoxRenderer.prototype.reset = function () {
  73643. this.renderList.reset();
  73644. };
  73645. BoundingBoxRenderer.prototype.render = function () {
  73646. if (this.renderList.length === 0) {
  73647. return;
  73648. }
  73649. this._prepareRessources();
  73650. if (!this._colorShader.isReady()) {
  73651. return;
  73652. }
  73653. var engine = this._scene.getEngine();
  73654. engine.setDepthWrite(false);
  73655. this._colorShader._preBind();
  73656. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73657. var boundingBox = this.renderList.data[boundingBoxIndex];
  73658. var min = boundingBox.minimum;
  73659. var max = boundingBox.maximum;
  73660. var diff = max.subtract(min);
  73661. var median = min.add(diff.scale(0.5));
  73662. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73663. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73664. .multiply(boundingBox.getWorldMatrix());
  73665. // VBOs
  73666. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73667. if (this.showBackLines) {
  73668. // Back
  73669. engine.setDepthFunctionToGreaterOrEqual();
  73670. this._scene.resetCachedMaterial();
  73671. this._colorShader.setColor4("color", this.backColor.toColor4());
  73672. this._colorShader.bind(worldMatrix);
  73673. // Draw order
  73674. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73675. }
  73676. // Front
  73677. engine.setDepthFunctionToLess();
  73678. this._scene.resetCachedMaterial();
  73679. this._colorShader.setColor4("color", this.frontColor.toColor4());
  73680. this._colorShader.bind(worldMatrix);
  73681. // Draw order
  73682. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73683. }
  73684. this._colorShader.unbind();
  73685. engine.setDepthFunctionToLessOrEqual();
  73686. engine.setDepthWrite(true);
  73687. };
  73688. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  73689. this._prepareRessources();
  73690. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  73691. return;
  73692. }
  73693. var engine = this._scene.getEngine();
  73694. engine.setDepthWrite(false);
  73695. engine.setColorWrite(false);
  73696. this._colorShader._preBind();
  73697. var boundingBox = mesh._boundingInfo.boundingBox;
  73698. var min = boundingBox.minimum;
  73699. var max = boundingBox.maximum;
  73700. var diff = max.subtract(min);
  73701. var median = min.add(diff.scale(0.5));
  73702. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73703. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73704. .multiply(boundingBox.getWorldMatrix());
  73705. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73706. engine.setDepthFunctionToLess();
  73707. this._scene.resetCachedMaterial();
  73708. this._colorShader.bind(worldMatrix);
  73709. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73710. this._colorShader.unbind();
  73711. engine.setDepthFunctionToLessOrEqual();
  73712. engine.setDepthWrite(true);
  73713. engine.setColorWrite(true);
  73714. };
  73715. BoundingBoxRenderer.prototype.dispose = function () {
  73716. if (!this._colorShader) {
  73717. return;
  73718. }
  73719. this.renderList.dispose();
  73720. this._colorShader.dispose();
  73721. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73722. if (buffer) {
  73723. buffer.dispose();
  73724. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73725. }
  73726. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73727. };
  73728. return BoundingBoxRenderer;
  73729. }());
  73730. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  73731. })(BABYLON || (BABYLON = {}));
  73732. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  73733. var BABYLON;
  73734. (function (BABYLON) {
  73735. var MorphTarget = /** @class */ (function () {
  73736. function MorphTarget(name, influence) {
  73737. if (influence === void 0) { influence = 0; }
  73738. this.name = name;
  73739. this.animations = new Array();
  73740. this._positions = null;
  73741. this._normals = null;
  73742. this._tangents = null;
  73743. this.onInfluenceChanged = new BABYLON.Observable();
  73744. this.influence = influence;
  73745. }
  73746. Object.defineProperty(MorphTarget.prototype, "influence", {
  73747. get: function () {
  73748. return this._influence;
  73749. },
  73750. set: function (influence) {
  73751. if (this._influence === influence) {
  73752. return;
  73753. }
  73754. var previous = this._influence;
  73755. this._influence = influence;
  73756. if (this.onInfluenceChanged.hasObservers) {
  73757. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  73758. }
  73759. },
  73760. enumerable: true,
  73761. configurable: true
  73762. });
  73763. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  73764. get: function () {
  73765. return !!this._positions;
  73766. },
  73767. enumerable: true,
  73768. configurable: true
  73769. });
  73770. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  73771. get: function () {
  73772. return !!this._normals;
  73773. },
  73774. enumerable: true,
  73775. configurable: true
  73776. });
  73777. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  73778. get: function () {
  73779. return !!this._tangents;
  73780. },
  73781. enumerable: true,
  73782. configurable: true
  73783. });
  73784. MorphTarget.prototype.setPositions = function (data) {
  73785. this._positions = data;
  73786. };
  73787. MorphTarget.prototype.getPositions = function () {
  73788. return this._positions;
  73789. };
  73790. MorphTarget.prototype.setNormals = function (data) {
  73791. this._normals = data;
  73792. };
  73793. MorphTarget.prototype.getNormals = function () {
  73794. return this._normals;
  73795. };
  73796. MorphTarget.prototype.setTangents = function (data) {
  73797. this._tangents = data;
  73798. };
  73799. MorphTarget.prototype.getTangents = function () {
  73800. return this._tangents;
  73801. };
  73802. /**
  73803. * Serializes the current target into a Serialization object.
  73804. * Returns the serialized object.
  73805. */
  73806. MorphTarget.prototype.serialize = function () {
  73807. var serializationObject = {};
  73808. serializationObject.name = this.name;
  73809. serializationObject.influence = this.influence;
  73810. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  73811. if (this.hasNormals) {
  73812. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  73813. }
  73814. if (this.hasTangents) {
  73815. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  73816. }
  73817. // Animations
  73818. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  73819. return serializationObject;
  73820. };
  73821. // Statics
  73822. MorphTarget.Parse = function (serializationObject) {
  73823. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  73824. result.setPositions(serializationObject.positions);
  73825. if (serializationObject.normals) {
  73826. result.setNormals(serializationObject.normals);
  73827. }
  73828. if (serializationObject.tangents) {
  73829. result.setTangents(serializationObject.tangents);
  73830. }
  73831. // Animations
  73832. if (serializationObject.animations) {
  73833. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  73834. var parsedAnimation = serializationObject.animations[animationIndex];
  73835. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73836. }
  73837. }
  73838. return result;
  73839. };
  73840. MorphTarget.FromMesh = function (mesh, name, influence) {
  73841. if (!name) {
  73842. name = mesh.name;
  73843. }
  73844. var result = new MorphTarget(name, influence);
  73845. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73846. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73847. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  73848. }
  73849. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  73850. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  73851. }
  73852. return result;
  73853. };
  73854. return MorphTarget;
  73855. }());
  73856. BABYLON.MorphTarget = MorphTarget;
  73857. })(BABYLON || (BABYLON = {}));
  73858. //# sourceMappingURL=babylon.morphTarget.js.map
  73859. var BABYLON;
  73860. (function (BABYLON) {
  73861. var MorphTargetManager = /** @class */ (function () {
  73862. function MorphTargetManager(scene) {
  73863. if (scene === void 0) { scene = null; }
  73864. this._targets = new Array();
  73865. this._targetObservable = new Array();
  73866. this._activeTargets = new BABYLON.SmartArray(16);
  73867. this._supportsNormals = false;
  73868. this._supportsTangents = false;
  73869. this._vertexCount = 0;
  73870. this._uniqueId = 0;
  73871. this._tempInfluences = new Array();
  73872. if (!scene) {
  73873. scene = BABYLON.Engine.LastCreatedScene;
  73874. }
  73875. this._scene = scene;
  73876. if (this._scene) {
  73877. this._scene.morphTargetManagers.push(this);
  73878. this._uniqueId = this._scene.getUniqueId();
  73879. }
  73880. }
  73881. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  73882. get: function () {
  73883. return this._uniqueId;
  73884. },
  73885. enumerable: true,
  73886. configurable: true
  73887. });
  73888. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  73889. get: function () {
  73890. return this._vertexCount;
  73891. },
  73892. enumerable: true,
  73893. configurable: true
  73894. });
  73895. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  73896. get: function () {
  73897. return this._supportsNormals;
  73898. },
  73899. enumerable: true,
  73900. configurable: true
  73901. });
  73902. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  73903. get: function () {
  73904. return this._supportsTangents;
  73905. },
  73906. enumerable: true,
  73907. configurable: true
  73908. });
  73909. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  73910. get: function () {
  73911. return this._targets.length;
  73912. },
  73913. enumerable: true,
  73914. configurable: true
  73915. });
  73916. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  73917. get: function () {
  73918. return this._activeTargets.length;
  73919. },
  73920. enumerable: true,
  73921. configurable: true
  73922. });
  73923. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  73924. get: function () {
  73925. return this._influences;
  73926. },
  73927. enumerable: true,
  73928. configurable: true
  73929. });
  73930. MorphTargetManager.prototype.getActiveTarget = function (index) {
  73931. return this._activeTargets.data[index];
  73932. };
  73933. MorphTargetManager.prototype.getTarget = function (index) {
  73934. return this._targets[index];
  73935. };
  73936. MorphTargetManager.prototype.addTarget = function (target) {
  73937. var _this = this;
  73938. this._targets.push(target);
  73939. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  73940. _this._syncActiveTargets(needUpdate);
  73941. }));
  73942. this._syncActiveTargets(true);
  73943. };
  73944. MorphTargetManager.prototype.removeTarget = function (target) {
  73945. var index = this._targets.indexOf(target);
  73946. if (index >= 0) {
  73947. this._targets.splice(index, 1);
  73948. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  73949. this._syncActiveTargets(true);
  73950. }
  73951. };
  73952. /**
  73953. * Serializes the current manager into a Serialization object.
  73954. * Returns the serialized object.
  73955. */
  73956. MorphTargetManager.prototype.serialize = function () {
  73957. var serializationObject = {};
  73958. serializationObject.id = this.uniqueId;
  73959. serializationObject.targets = [];
  73960. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73961. var target = _a[_i];
  73962. serializationObject.targets.push(target.serialize());
  73963. }
  73964. return serializationObject;
  73965. };
  73966. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  73967. var influenceCount = 0;
  73968. this._activeTargets.reset();
  73969. this._supportsNormals = true;
  73970. this._supportsTangents = true;
  73971. this._vertexCount = 0;
  73972. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  73973. var target = _a[_i];
  73974. this._activeTargets.push(target);
  73975. this._tempInfluences[influenceCount++] = target.influence;
  73976. var positions = target.getPositions();
  73977. if (positions) {
  73978. this._supportsNormals = this._supportsNormals && target.hasNormals;
  73979. this._supportsTangents = this._supportsTangents && target.hasTangents;
  73980. var vertexCount = positions.length / 3;
  73981. if (this._vertexCount === 0) {
  73982. this._vertexCount = vertexCount;
  73983. }
  73984. else if (this._vertexCount !== vertexCount) {
  73985. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  73986. return;
  73987. }
  73988. }
  73989. }
  73990. if (!this._influences || this._influences.length !== influenceCount) {
  73991. this._influences = new Float32Array(influenceCount);
  73992. }
  73993. for (var index = 0; index < influenceCount; index++) {
  73994. this._influences[index] = this._tempInfluences[index];
  73995. }
  73996. if (needUpdate && this._scene) {
  73997. // Flag meshes as dirty to resync with the active targets
  73998. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  73999. var mesh = _c[_b];
  74000. if (mesh.morphTargetManager === this) {
  74001. mesh._syncGeometryWithMorphTargetManager();
  74002. }
  74003. }
  74004. }
  74005. };
  74006. // Statics
  74007. MorphTargetManager.Parse = function (serializationObject, scene) {
  74008. var result = new MorphTargetManager(scene);
  74009. result._uniqueId = serializationObject.id;
  74010. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  74011. var targetData = _a[_i];
  74012. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  74013. }
  74014. return result;
  74015. };
  74016. return MorphTargetManager;
  74017. }());
  74018. BABYLON.MorphTargetManager = MorphTargetManager;
  74019. })(BABYLON || (BABYLON = {}));
  74020. //# sourceMappingURL=babylon.morphTargetManager.js.map
  74021. var BABYLON;
  74022. (function (BABYLON) {
  74023. var Octree = /** @class */ (function () {
  74024. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  74025. if (maxDepth === void 0) { maxDepth = 2; }
  74026. this.maxDepth = maxDepth;
  74027. this.dynamicContent = new Array();
  74028. this._maxBlockCapacity = maxBlockCapacity || 64;
  74029. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  74030. this._creationFunc = creationFunc;
  74031. }
  74032. // Methods
  74033. Octree.prototype.update = function (worldMin, worldMax, entries) {
  74034. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  74035. };
  74036. Octree.prototype.addMesh = function (entry) {
  74037. for (var index = 0; index < this.blocks.length; index++) {
  74038. var block = this.blocks[index];
  74039. block.addEntry(entry);
  74040. }
  74041. };
  74042. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  74043. this._selectionContent.reset();
  74044. for (var index = 0; index < this.blocks.length; index++) {
  74045. var block = this.blocks[index];
  74046. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  74047. }
  74048. if (allowDuplicate) {
  74049. this._selectionContent.concat(this.dynamicContent);
  74050. }
  74051. else {
  74052. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74053. }
  74054. return this._selectionContent;
  74055. };
  74056. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  74057. this._selectionContent.reset();
  74058. for (var index = 0; index < this.blocks.length; index++) {
  74059. var block = this.blocks[index];
  74060. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  74061. }
  74062. if (allowDuplicate) {
  74063. this._selectionContent.concat(this.dynamicContent);
  74064. }
  74065. else {
  74066. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74067. }
  74068. return this._selectionContent;
  74069. };
  74070. Octree.prototype.intersectsRay = function (ray) {
  74071. this._selectionContent.reset();
  74072. for (var index = 0; index < this.blocks.length; index++) {
  74073. var block = this.blocks[index];
  74074. block.intersectsRay(ray, this._selectionContent);
  74075. }
  74076. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74077. return this._selectionContent;
  74078. };
  74079. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  74080. target.blocks = new Array();
  74081. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  74082. // Segmenting space
  74083. for (var x = 0; x < 2; x++) {
  74084. for (var y = 0; y < 2; y++) {
  74085. for (var z = 0; z < 2; z++) {
  74086. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  74087. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  74088. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  74089. block.addEntries(entries);
  74090. target.blocks.push(block);
  74091. }
  74092. }
  74093. }
  74094. };
  74095. Octree.CreationFuncForMeshes = function (entry, block) {
  74096. var boundingInfo = entry.getBoundingInfo();
  74097. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74098. block.entries.push(entry);
  74099. }
  74100. };
  74101. Octree.CreationFuncForSubMeshes = function (entry, block) {
  74102. var boundingInfo = entry.getBoundingInfo();
  74103. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74104. block.entries.push(entry);
  74105. }
  74106. };
  74107. return Octree;
  74108. }());
  74109. BABYLON.Octree = Octree;
  74110. })(BABYLON || (BABYLON = {}));
  74111. //# sourceMappingURL=babylon.octree.js.map
  74112. var BABYLON;
  74113. (function (BABYLON) {
  74114. var OctreeBlock = /** @class */ (function () {
  74115. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  74116. this.entries = new Array();
  74117. this._boundingVectors = new Array();
  74118. this._capacity = capacity;
  74119. this._depth = depth;
  74120. this._maxDepth = maxDepth;
  74121. this._creationFunc = creationFunc;
  74122. this._minPoint = minPoint;
  74123. this._maxPoint = maxPoint;
  74124. this._boundingVectors.push(minPoint.clone());
  74125. this._boundingVectors.push(maxPoint.clone());
  74126. this._boundingVectors.push(minPoint.clone());
  74127. this._boundingVectors[2].x = maxPoint.x;
  74128. this._boundingVectors.push(minPoint.clone());
  74129. this._boundingVectors[3].y = maxPoint.y;
  74130. this._boundingVectors.push(minPoint.clone());
  74131. this._boundingVectors[4].z = maxPoint.z;
  74132. this._boundingVectors.push(maxPoint.clone());
  74133. this._boundingVectors[5].z = minPoint.z;
  74134. this._boundingVectors.push(maxPoint.clone());
  74135. this._boundingVectors[6].x = minPoint.x;
  74136. this._boundingVectors.push(maxPoint.clone());
  74137. this._boundingVectors[7].y = minPoint.y;
  74138. }
  74139. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  74140. // Property
  74141. get: function () {
  74142. return this._capacity;
  74143. },
  74144. enumerable: true,
  74145. configurable: true
  74146. });
  74147. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  74148. get: function () {
  74149. return this._minPoint;
  74150. },
  74151. enumerable: true,
  74152. configurable: true
  74153. });
  74154. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  74155. get: function () {
  74156. return this._maxPoint;
  74157. },
  74158. enumerable: true,
  74159. configurable: true
  74160. });
  74161. // Methods
  74162. OctreeBlock.prototype.addEntry = function (entry) {
  74163. if (this.blocks) {
  74164. for (var index = 0; index < this.blocks.length; index++) {
  74165. var block = this.blocks[index];
  74166. block.addEntry(entry);
  74167. }
  74168. return;
  74169. }
  74170. this._creationFunc(entry, this);
  74171. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  74172. this.createInnerBlocks();
  74173. }
  74174. };
  74175. OctreeBlock.prototype.addEntries = function (entries) {
  74176. for (var index = 0; index < entries.length; index++) {
  74177. var mesh = entries[index];
  74178. this.addEntry(mesh);
  74179. }
  74180. };
  74181. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  74182. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  74183. if (this.blocks) {
  74184. for (var index = 0; index < this.blocks.length; index++) {
  74185. var block = this.blocks[index];
  74186. block.select(frustumPlanes, selection, allowDuplicate);
  74187. }
  74188. return;
  74189. }
  74190. if (allowDuplicate) {
  74191. selection.concat(this.entries);
  74192. }
  74193. else {
  74194. selection.concatWithNoDuplicate(this.entries);
  74195. }
  74196. }
  74197. };
  74198. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  74199. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  74200. if (this.blocks) {
  74201. for (var index = 0; index < this.blocks.length; index++) {
  74202. var block = this.blocks[index];
  74203. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  74204. }
  74205. return;
  74206. }
  74207. if (allowDuplicate) {
  74208. selection.concat(this.entries);
  74209. }
  74210. else {
  74211. selection.concatWithNoDuplicate(this.entries);
  74212. }
  74213. }
  74214. };
  74215. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  74216. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  74217. if (this.blocks) {
  74218. for (var index = 0; index < this.blocks.length; index++) {
  74219. var block = this.blocks[index];
  74220. block.intersectsRay(ray, selection);
  74221. }
  74222. return;
  74223. }
  74224. selection.concatWithNoDuplicate(this.entries);
  74225. }
  74226. };
  74227. OctreeBlock.prototype.createInnerBlocks = function () {
  74228. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  74229. };
  74230. return OctreeBlock;
  74231. }());
  74232. BABYLON.OctreeBlock = OctreeBlock;
  74233. })(BABYLON || (BABYLON = {}));
  74234. //# sourceMappingURL=babylon.octreeBlock.js.map
  74235. var BABYLON;
  74236. (function (BABYLON) {
  74237. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  74238. __extends(VRDistortionCorrectionPostProcess, _super);
  74239. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  74240. var _this = _super.call(this, name, "vrDistortionCorrection", [
  74241. 'LensCenter',
  74242. 'Scale',
  74243. 'ScaleIn',
  74244. 'HmdWarpParam'
  74245. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  74246. _this._isRightEye = isRightEye;
  74247. _this._distortionFactors = vrMetrics.distortionK;
  74248. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  74249. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  74250. _this.adaptScaleToCurrentViewport = true;
  74251. _this.onSizeChangedObservable.add(function () {
  74252. _this.aspectRatio = _this.width * .5 / _this.height;
  74253. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  74254. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  74255. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  74256. });
  74257. _this.onApplyObservable.add(function (effect) {
  74258. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  74259. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  74260. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  74261. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  74262. });
  74263. return _this;
  74264. }
  74265. return VRDistortionCorrectionPostProcess;
  74266. }(BABYLON.PostProcess));
  74267. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  74268. })(BABYLON || (BABYLON = {}));
  74269. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  74270. var BABYLON;
  74271. (function (BABYLON) {
  74272. var AnaglyphPostProcess = /** @class */ (function (_super) {
  74273. __extends(AnaglyphPostProcess, _super);
  74274. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  74275. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  74276. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74277. _this.onApplyObservable.add(function (effect) {
  74278. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  74279. });
  74280. return _this;
  74281. }
  74282. return AnaglyphPostProcess;
  74283. }(BABYLON.PostProcess));
  74284. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  74285. })(BABYLON || (BABYLON = {}));
  74286. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  74287. var BABYLON;
  74288. (function (BABYLON) {
  74289. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  74290. __extends(StereoscopicInterlacePostProcess, _super);
  74291. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  74292. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  74293. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74294. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74295. _this.onSizeChangedObservable.add(function () {
  74296. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74297. });
  74298. _this.onApplyObservable.add(function (effect) {
  74299. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  74300. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  74301. });
  74302. return _this;
  74303. }
  74304. return StereoscopicInterlacePostProcess;
  74305. }(BABYLON.PostProcess));
  74306. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  74307. })(BABYLON || (BABYLON = {}));
  74308. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  74309. var BABYLON;
  74310. (function (BABYLON) {
  74311. /**
  74312. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  74313. * Screen rotation is taken into account.
  74314. */
  74315. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  74316. function FreeCameraDeviceOrientationInput() {
  74317. var _this = this;
  74318. this._screenOrientationAngle = 0;
  74319. this._screenQuaternion = new BABYLON.Quaternion();
  74320. this._alpha = 0;
  74321. this._beta = 0;
  74322. this._gamma = 0;
  74323. this._orientationChanged = function () {
  74324. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  74325. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  74326. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  74327. };
  74328. this._deviceOrientation = function (evt) {
  74329. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  74330. _this._beta = evt.beta !== null ? evt.beta : 0;
  74331. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  74332. };
  74333. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  74334. this._orientationChanged();
  74335. }
  74336. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  74337. get: function () {
  74338. return this._camera;
  74339. },
  74340. set: function (camera) {
  74341. this._camera = camera;
  74342. if (this._camera != null && !this._camera.rotationQuaternion) {
  74343. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  74344. }
  74345. },
  74346. enumerable: true,
  74347. configurable: true
  74348. });
  74349. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74350. window.addEventListener("orientationchange", this._orientationChanged);
  74351. window.addEventListener("deviceorientation", this._deviceOrientation);
  74352. //In certain cases, the attach control is called AFTER orientation was changed,
  74353. //So this is needed.
  74354. this._orientationChanged();
  74355. };
  74356. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  74357. window.removeEventListener("orientationchange", this._orientationChanged);
  74358. window.removeEventListener("deviceorientation", this._deviceOrientation);
  74359. };
  74360. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  74361. //if no device orientation provided, don't update the rotation.
  74362. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  74363. if (!this._alpha)
  74364. return;
  74365. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  74366. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  74367. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  74368. //Mirror on XY Plane
  74369. this._camera.rotationQuaternion.z *= -1;
  74370. this._camera.rotationQuaternion.w *= -1;
  74371. };
  74372. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  74373. return "FreeCameraDeviceOrientationInput";
  74374. };
  74375. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  74376. return "deviceOrientation";
  74377. };
  74378. return FreeCameraDeviceOrientationInput;
  74379. }());
  74380. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  74381. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  74382. })(BABYLON || (BABYLON = {}));
  74383. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  74384. var BABYLON;
  74385. (function (BABYLON) {
  74386. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  74387. function ArcRotateCameraVRDeviceOrientationInput() {
  74388. this.alphaCorrection = 1;
  74389. this.betaCorrection = 1;
  74390. this.gammaCorrection = 1;
  74391. this._alpha = 0;
  74392. this._gamma = 0;
  74393. this._dirty = false;
  74394. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  74395. }
  74396. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74397. this.camera.attachControl(element, noPreventDefault);
  74398. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  74399. };
  74400. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  74401. if (evt.alpha !== null) {
  74402. this._alpha = +evt.alpha | 0;
  74403. }
  74404. if (evt.gamma !== null) {
  74405. this._gamma = +evt.gamma | 0;
  74406. }
  74407. this._dirty = true;
  74408. };
  74409. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  74410. if (this._dirty) {
  74411. this._dirty = false;
  74412. if (this._gamma < 0) {
  74413. this._gamma = 180 + this._gamma;
  74414. }
  74415. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  74416. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  74417. }
  74418. };
  74419. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  74420. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  74421. };
  74422. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  74423. return "ArcRotateCameraVRDeviceOrientationInput";
  74424. };
  74425. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  74426. return "VRDeviceOrientation";
  74427. };
  74428. return ArcRotateCameraVRDeviceOrientationInput;
  74429. }());
  74430. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  74431. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  74432. })(BABYLON || (BABYLON = {}));
  74433. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74434. var BABYLON;
  74435. (function (BABYLON) {
  74436. var VRCameraMetrics = /** @class */ (function () {
  74437. function VRCameraMetrics() {
  74438. this.compensateDistortion = true;
  74439. }
  74440. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74441. get: function () {
  74442. return this.hResolution / (2 * this.vResolution);
  74443. },
  74444. enumerable: true,
  74445. configurable: true
  74446. });
  74447. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74448. get: function () {
  74449. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74450. },
  74451. enumerable: true,
  74452. configurable: true
  74453. });
  74454. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74455. get: function () {
  74456. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74457. var h = (4 * meters) / this.hScreenSize;
  74458. return BABYLON.Matrix.Translation(h, 0, 0);
  74459. },
  74460. enumerable: true,
  74461. configurable: true
  74462. });
  74463. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74464. get: function () {
  74465. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74466. var h = (4 * meters) / this.hScreenSize;
  74467. return BABYLON.Matrix.Translation(-h, 0, 0);
  74468. },
  74469. enumerable: true,
  74470. configurable: true
  74471. });
  74472. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74473. get: function () {
  74474. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74475. },
  74476. enumerable: true,
  74477. configurable: true
  74478. });
  74479. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74480. get: function () {
  74481. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74482. },
  74483. enumerable: true,
  74484. configurable: true
  74485. });
  74486. VRCameraMetrics.GetDefault = function () {
  74487. var result = new VRCameraMetrics();
  74488. result.hResolution = 1280;
  74489. result.vResolution = 800;
  74490. result.hScreenSize = 0.149759993;
  74491. result.vScreenSize = 0.0935999975;
  74492. result.vScreenCenter = 0.0467999987;
  74493. result.eyeToScreenDistance = 0.0410000011;
  74494. result.lensSeparationDistance = 0.0635000020;
  74495. result.interpupillaryDistance = 0.0640000030;
  74496. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74497. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74498. result.postProcessScaleFactor = 1.714605507808412;
  74499. result.lensCenterOffset = 0.151976421;
  74500. return result;
  74501. };
  74502. return VRCameraMetrics;
  74503. }());
  74504. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74505. })(BABYLON || (BABYLON = {}));
  74506. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74507. var BABYLON;
  74508. (function (BABYLON) {
  74509. /**
  74510. * This represents a WebVR camera.
  74511. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  74512. * @example http://doc.babylonjs.com/how_to/webvr_camera
  74513. */
  74514. var WebVRFreeCamera = /** @class */ (function (_super) {
  74515. __extends(WebVRFreeCamera, _super);
  74516. /**
  74517. * Instantiates a WebVRFreeCamera.
  74518. * @param name The name of the WebVRFreeCamera
  74519. * @param position The starting anchor position for the camera
  74520. * @param scene The scene the camera belongs to
  74521. * @param webVROptions a set of customizable options for the webVRCamera
  74522. */
  74523. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74524. if (webVROptions === void 0) { webVROptions = {}; }
  74525. var _this = _super.call(this, name, position, scene) || this;
  74526. _this.webVROptions = webVROptions;
  74527. /**
  74528. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  74529. */
  74530. _this._vrDevice = null;
  74531. /**
  74532. * The rawPose of the vrDevice.
  74533. */
  74534. _this.rawPose = null;
  74535. _this._specsVersion = "1.1";
  74536. _this._attached = false;
  74537. _this._descendants = [];
  74538. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74539. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74540. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74541. _this._standingMatrix = null;
  74542. /**
  74543. * Represents device position in babylon space.
  74544. */
  74545. _this.devicePosition = BABYLON.Vector3.Zero();
  74546. /**
  74547. * Represents device rotation in babylon space.
  74548. */
  74549. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74550. /**
  74551. * The scale of the device to be used when translating from device space to babylon space.
  74552. */
  74553. _this.deviceScaleFactor = 1;
  74554. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74555. _this._worldToDevice = BABYLON.Matrix.Identity();
  74556. /**
  74557. * References to the webVR controllers for the vrDevice.
  74558. */
  74559. _this.controllers = [];
  74560. /**
  74561. * Emits an event when a controller is attached.
  74562. */
  74563. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74564. /**
  74565. * Emits an event when a controller's mesh has been loaded;
  74566. */
  74567. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74568. /**
  74569. * If the rig cameras be used as parent instead of this camera.
  74570. */
  74571. _this.rigParenting = true;
  74572. _this._defaultHeight = undefined;
  74573. _this._workingVector = BABYLON.Vector3.Zero();
  74574. _this._oneVector = BABYLON.Vector3.One();
  74575. _this._workingMatrix = BABYLON.Matrix.Identity();
  74576. _this._cache.position = BABYLON.Vector3.Zero();
  74577. if (webVROptions.defaultHeight) {
  74578. _this._defaultHeight = webVROptions.defaultHeight;
  74579. _this.position.y = _this._defaultHeight;
  74580. }
  74581. _this.minZ = 0.1;
  74582. //legacy support - the compensation boolean was removed.
  74583. if (arguments.length === 5) {
  74584. _this.webVROptions = arguments[4];
  74585. }
  74586. // default webVR options
  74587. if (_this.webVROptions.trackPosition == undefined) {
  74588. _this.webVROptions.trackPosition = true;
  74589. }
  74590. if (_this.webVROptions.controllerMeshes == undefined) {
  74591. _this.webVROptions.controllerMeshes = true;
  74592. }
  74593. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74594. _this.webVROptions.defaultLightingOnControllers = true;
  74595. }
  74596. _this.rotationQuaternion = new BABYLON.Quaternion();
  74597. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74598. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74599. }
  74600. //enable VR
  74601. var engine = _this.getEngine();
  74602. _this._onVREnabled = function (success) { if (success) {
  74603. _this.initControllers();
  74604. } };
  74605. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74606. engine.initWebVR().add(function (event) {
  74607. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74608. return;
  74609. }
  74610. _this._vrDevice = event.vrDisplay;
  74611. //reset the rig parameters.
  74612. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74613. if (_this._attached) {
  74614. _this.getEngine().enableVR();
  74615. }
  74616. });
  74617. if (typeof (VRFrameData) !== "undefined")
  74618. _this._frameData = new VRFrameData();
  74619. /**
  74620. * The idea behind the following lines:
  74621. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74622. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74623. * the second will not show it correctly.
  74624. *
  74625. * To solve this - each object that has the camera as parent will be added to a protected array.
  74626. * When the rig camera renders, it will take this array and set all of those to be its children.
  74627. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74628. * Amazing!
  74629. */
  74630. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74631. if (camera.parent === _this && _this.rigParenting) {
  74632. _this._descendants = _this.getDescendants(true, function (n) {
  74633. // don't take the cameras or the controllers!
  74634. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74635. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74636. return !isController && !isRigCamera;
  74637. });
  74638. _this._descendants.forEach(function (node) {
  74639. node.parent = camera;
  74640. });
  74641. }
  74642. });
  74643. scene.onAfterCameraRenderObservable.add(function (camera) {
  74644. if (camera.parent === _this && _this.rigParenting) {
  74645. _this._descendants.forEach(function (node) {
  74646. node.parent = _this;
  74647. });
  74648. }
  74649. });
  74650. return _this;
  74651. }
  74652. /**
  74653. * Gets the device distance from the ground.
  74654. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  74655. */
  74656. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  74657. if (this._standingMatrix && this._defaultHeight === undefined) {
  74658. // Add standing matrix offset to get real offset from ground in room
  74659. this._standingMatrix.getTranslationToRef(this._workingVector);
  74660. return this._deviceRoomPosition.y + this._workingVector.y;
  74661. }
  74662. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74663. return this._defaultHeight || 0;
  74664. };
  74665. /**
  74666. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  74667. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  74668. */
  74669. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  74670. var _this = this;
  74671. if (callback === void 0) { callback = function (bool) { }; }
  74672. // Use standing matrix if available
  74673. if (!navigator || !navigator.getVRDisplays) {
  74674. callback(false);
  74675. }
  74676. else {
  74677. navigator.getVRDisplays().then(function (displays) {
  74678. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  74679. callback(false);
  74680. }
  74681. else {
  74682. _this._standingMatrix = new BABYLON.Matrix();
  74683. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  74684. if (!_this.getScene().useRightHandedSystem) {
  74685. [2, 6, 8, 9, 14].forEach(function (num) {
  74686. if (_this._standingMatrix) {
  74687. _this._standingMatrix.m[num] *= -1;
  74688. }
  74689. });
  74690. }
  74691. callback(true);
  74692. }
  74693. });
  74694. }
  74695. };
  74696. /**
  74697. * Disposes the camera
  74698. */
  74699. WebVRFreeCamera.prototype.dispose = function () {
  74700. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  74701. _super.prototype.dispose.call(this);
  74702. };
  74703. /**
  74704. * Gets a vrController by name.
  74705. * @param name The name of the controller to retreive
  74706. * @returns the controller matching the name specified or null if not found
  74707. */
  74708. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  74709. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  74710. var gp = _a[_i];
  74711. if (gp.hand === name) {
  74712. return gp;
  74713. }
  74714. }
  74715. return null;
  74716. };
  74717. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  74718. /**
  74719. * The controller corrisponding to the users left hand.
  74720. */
  74721. get: function () {
  74722. if (!this._leftController) {
  74723. this._leftController = this.getControllerByName("left");
  74724. }
  74725. return this._leftController;
  74726. },
  74727. enumerable: true,
  74728. configurable: true
  74729. });
  74730. ;
  74731. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  74732. /**
  74733. * The controller corrisponding to the users right hand.
  74734. */
  74735. get: function () {
  74736. if (!this._rightController) {
  74737. this._rightController = this.getControllerByName("right");
  74738. }
  74739. return this._rightController;
  74740. },
  74741. enumerable: true,
  74742. configurable: true
  74743. });
  74744. ;
  74745. /**
  74746. * Casts a ray forward from the vrCamera's gaze.
  74747. * @param length Length of the ray (default: 100)
  74748. * @returns the ray corrisponding to the gaze
  74749. */
  74750. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  74751. if (length === void 0) { length = 100; }
  74752. if (this.leftCamera) {
  74753. // Use left eye to avoid computation to compute center on every call
  74754. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  74755. }
  74756. else {
  74757. return _super.prototype.getForwardRay.call(this, length);
  74758. }
  74759. };
  74760. /**
  74761. * Updates the camera based on device's frame data
  74762. */
  74763. WebVRFreeCamera.prototype._checkInputs = function () {
  74764. if (this._vrDevice && this._vrDevice.isPresenting) {
  74765. this._vrDevice.getFrameData(this._frameData);
  74766. this.updateFromDevice(this._frameData.pose);
  74767. }
  74768. _super.prototype._checkInputs.call(this);
  74769. };
  74770. /**
  74771. * Updates the poseControlled values based on the input device pose.
  74772. * @param poseData Pose coming from the device
  74773. */
  74774. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  74775. if (poseData && poseData.orientation) {
  74776. this.rawPose = poseData;
  74777. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  74778. if (this.getScene().useRightHandedSystem) {
  74779. this._deviceRoomRotationQuaternion.z *= -1;
  74780. this._deviceRoomRotationQuaternion.w *= -1;
  74781. }
  74782. if (this.webVROptions.trackPosition && this.rawPose.position) {
  74783. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  74784. if (this.getScene().useRightHandedSystem) {
  74785. this._deviceRoomPosition.z *= -1;
  74786. }
  74787. }
  74788. }
  74789. };
  74790. /**
  74791. * WebVR's attach control will start broadcasting frames to the device.
  74792. * Note that in certain browsers (chrome for example) this function must be called
  74793. * within a user-interaction callback. Example:
  74794. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  74795. *
  74796. * @param element html element to attach the vrDevice to
  74797. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  74798. */
  74799. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  74800. _super.prototype.attachControl.call(this, element, noPreventDefault);
  74801. this._attached = true;
  74802. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  74803. if (this._vrDevice) {
  74804. this.getEngine().enableVR();
  74805. }
  74806. };
  74807. /**
  74808. * Detaches the camera from the html element and disables VR
  74809. *
  74810. * @param element html element to detach from
  74811. */
  74812. WebVRFreeCamera.prototype.detachControl = function (element) {
  74813. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74814. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74815. _super.prototype.detachControl.call(this, element);
  74816. this._attached = false;
  74817. this.getEngine().disableVR();
  74818. };
  74819. /**
  74820. * @returns the name of this class
  74821. */
  74822. WebVRFreeCamera.prototype.getClassName = function () {
  74823. return "WebVRFreeCamera";
  74824. };
  74825. /**
  74826. * Calls resetPose on the vrDisplay
  74827. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  74828. */
  74829. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  74830. //uses the vrDisplay's "resetPose()".
  74831. //pitch and roll won't be affected.
  74832. this._vrDevice.resetPose();
  74833. };
  74834. /**
  74835. * Updates the rig cameras (left and right eye)
  74836. */
  74837. WebVRFreeCamera.prototype._updateRigCameras = function () {
  74838. var camLeft = this._rigCameras[0];
  74839. var camRight = this._rigCameras[1];
  74840. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74841. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74842. camLeft.position.copyFrom(this._deviceRoomPosition);
  74843. camRight.position.copyFrom(this._deviceRoomPosition);
  74844. };
  74845. /**
  74846. * Updates the cached values of the camera
  74847. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  74848. */
  74849. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  74850. var _this = this;
  74851. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  74852. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  74853. if (!this.updateCacheCalled) {
  74854. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  74855. this.updateCacheCalled = true;
  74856. this.update();
  74857. }
  74858. // Set working vector to the device position in room space rotated by the new rotation
  74859. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  74860. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  74861. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  74862. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  74863. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  74864. // Add translation from anchor position
  74865. this._deviceToWorld.getTranslationToRef(this._workingVector);
  74866. this._workingVector.addInPlace(this.position);
  74867. this._workingVector.subtractInPlace(this._cache.position);
  74868. this._deviceToWorld.setTranslation(this._workingVector);
  74869. // Set an inverted matrix to be used when updating the camera
  74870. this._deviceToWorld.invertToRef(this._worldToDevice);
  74871. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  74872. this.controllers.forEach(function (controller) {
  74873. controller._deviceToWorld = _this._deviceToWorld;
  74874. controller.update();
  74875. });
  74876. }
  74877. if (!ignoreParentClass) {
  74878. _super.prototype._updateCache.call(this);
  74879. }
  74880. this.updateCacheCalled = false;
  74881. };
  74882. /**
  74883. * Updates the current device position and rotation in the babylon world
  74884. */
  74885. WebVRFreeCamera.prototype.update = function () {
  74886. // Get current device position in babylon world
  74887. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  74888. // Get current device rotation in babylon world
  74889. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  74890. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  74891. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74892. _super.prototype.update.call(this);
  74893. };
  74894. /**
  74895. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  74896. * @returns an identity matrix
  74897. */
  74898. WebVRFreeCamera.prototype._getViewMatrix = function () {
  74899. return BABYLON.Matrix.Identity();
  74900. };
  74901. /**
  74902. * This function is called by the two RIG cameras.
  74903. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  74904. */
  74905. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  74906. var _this = this;
  74907. //WebVR 1.1
  74908. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  74909. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  74910. if (!this.getScene().useRightHandedSystem) {
  74911. [2, 6, 8, 9, 14].forEach(function (num) {
  74912. _this._webvrViewMatrix.m[num] *= -1;
  74913. });
  74914. }
  74915. // update the camera rotation matrix
  74916. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  74917. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  74918. // Computing target and final matrix
  74919. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  74920. var parentCamera = this._cameraRigParams["parentCamera"];
  74921. // should the view matrix be updated with scale and position offset?
  74922. if (parentCamera.deviceScaleFactor !== 1) {
  74923. this._webvrViewMatrix.invert();
  74924. // scale the position, if set
  74925. if (parentCamera.deviceScaleFactor) {
  74926. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  74927. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  74928. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  74929. }
  74930. this._webvrViewMatrix.invert();
  74931. }
  74932. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  74933. return this._webvrViewMatrix;
  74934. };
  74935. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  74936. var _this = this;
  74937. var parentCamera = this.parent;
  74938. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  74939. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  74940. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  74941. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  74942. //babylon compatible matrix
  74943. if (!this.getScene().useRightHandedSystem) {
  74944. [8, 9, 10, 11].forEach(function (num) {
  74945. _this._projectionMatrix.m[num] *= -1;
  74946. });
  74947. }
  74948. return this._projectionMatrix;
  74949. };
  74950. /**
  74951. * Initializes the controllers and their meshes
  74952. */
  74953. WebVRFreeCamera.prototype.initControllers = function () {
  74954. var _this = this;
  74955. this.controllers = [];
  74956. var manager = this.getScene().gamepadManager;
  74957. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  74958. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74959. var webVrController = gamepad;
  74960. if (webVrController.defaultModel) {
  74961. webVrController.defaultModel.setEnabled(false);
  74962. }
  74963. if (webVrController.hand === "right") {
  74964. _this._rightController = null;
  74965. }
  74966. if (webVrController.hand === "left") {
  74967. _this._rightController = null;
  74968. }
  74969. var controllerIndex = _this.controllers.indexOf(webVrController);
  74970. if (controllerIndex !== -1) {
  74971. _this.controllers.splice(controllerIndex, 1);
  74972. }
  74973. }
  74974. });
  74975. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  74976. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  74977. var webVrController_1 = gamepad;
  74978. webVrController_1._deviceToWorld = _this._deviceToWorld;
  74979. if (_this.webVROptions.controllerMeshes) {
  74980. if (webVrController_1.defaultModel) {
  74981. webVrController_1.defaultModel.setEnabled(true);
  74982. }
  74983. else {
  74984. // Load the meshes
  74985. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  74986. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  74987. if (_this.webVROptions.defaultLightingOnControllers) {
  74988. if (!_this._lightOnControllers) {
  74989. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  74990. }
  74991. var activateLightOnSubMeshes_1 = function (mesh, light) {
  74992. var children = mesh.getChildren();
  74993. if (children.length !== 0) {
  74994. children.forEach(function (mesh) {
  74995. light.includedOnlyMeshes.push(mesh);
  74996. activateLightOnSubMeshes_1(mesh, light);
  74997. });
  74998. }
  74999. };
  75000. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  75001. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  75002. }
  75003. });
  75004. }
  75005. }
  75006. webVrController_1.attachToPoseControlledCamera(_this);
  75007. // since this is async - sanity check. Is the controller already stored?
  75008. if (_this.controllers.indexOf(webVrController_1) === -1) {
  75009. //add to the controllers array
  75010. _this.controllers.push(webVrController_1);
  75011. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  75012. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  75013. // So we're overriding setting left & right manually to be sure
  75014. var firstViveWandDetected = false;
  75015. for (var i = 0; i < _this.controllers.length; i++) {
  75016. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75017. if (!firstViveWandDetected) {
  75018. firstViveWandDetected = true;
  75019. _this.controllers[i].hand = "left";
  75020. }
  75021. else {
  75022. _this.controllers[i].hand = "right";
  75023. }
  75024. }
  75025. }
  75026. //did we find enough controllers? Great! let the developer know.
  75027. if (_this.controllers.length >= 2) {
  75028. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  75029. }
  75030. }
  75031. }
  75032. });
  75033. };
  75034. return WebVRFreeCamera;
  75035. }(BABYLON.FreeCamera));
  75036. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  75037. })(BABYLON || (BABYLON = {}));
  75038. //# sourceMappingURL=babylon.webVRCamera.js.map
  75039. var BABYLON;
  75040. (function (BABYLON) {
  75041. // We're mainly based on the logic defined into the FreeCamera code
  75042. /**
  75043. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  75044. * being tilted forward or back and left or right.
  75045. */
  75046. var DeviceOrientationCamera = /** @class */ (function (_super) {
  75047. __extends(DeviceOrientationCamera, _super);
  75048. /**
  75049. * Creates a new device orientation camera. @see DeviceOrientationCamera
  75050. * @param name The name of the camera
  75051. * @param position The start position camera
  75052. * @param scene The scene the camera belongs to
  75053. */
  75054. function DeviceOrientationCamera(name, position, scene) {
  75055. var _this = _super.call(this, name, position, scene) || this;
  75056. _this._quaternionCache = new BABYLON.Quaternion();
  75057. _this.inputs.addDeviceOrientation();
  75058. return _this;
  75059. }
  75060. /**
  75061. * Gets the current instance class name ("DeviceOrientationCamera").
  75062. * This helps avoiding instanceof at run time.
  75063. * @returns the class name
  75064. */
  75065. DeviceOrientationCamera.prototype.getClassName = function () {
  75066. return "DeviceOrientationCamera";
  75067. };
  75068. /**
  75069. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  75070. */
  75071. DeviceOrientationCamera.prototype._checkInputs = function () {
  75072. _super.prototype._checkInputs.call(this);
  75073. this._quaternionCache.copyFrom(this.rotationQuaternion);
  75074. if (this._initialQuaternion) {
  75075. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75076. }
  75077. };
  75078. /**
  75079. * Reset the camera to its default orientation on the specified axis only.
  75080. * @param axis The axis to reset
  75081. */
  75082. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  75083. var _this = this;
  75084. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  75085. //can only work if this camera has a rotation quaternion already.
  75086. if (!this.rotationQuaternion)
  75087. return;
  75088. if (!this._initialQuaternion) {
  75089. this._initialQuaternion = new BABYLON.Quaternion();
  75090. }
  75091. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  75092. ['x', 'y', 'z'].forEach(function (axisName) {
  75093. if (!axis[axisName]) {
  75094. _this._initialQuaternion[axisName] = 0;
  75095. }
  75096. else {
  75097. _this._initialQuaternion[axisName] *= -1;
  75098. }
  75099. });
  75100. this._initialQuaternion.normalize();
  75101. //force rotation update
  75102. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75103. };
  75104. return DeviceOrientationCamera;
  75105. }(BABYLON.FreeCamera));
  75106. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  75107. })(BABYLON || (BABYLON = {}));
  75108. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  75109. var BABYLON;
  75110. (function (BABYLON) {
  75111. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  75112. __extends(VRDeviceOrientationFreeCamera, _super);
  75113. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75114. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75115. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75116. var _this = _super.call(this, name, position, scene) || this;
  75117. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75118. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75119. return _this;
  75120. }
  75121. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  75122. return "VRDeviceOrientationFreeCamera";
  75123. };
  75124. return VRDeviceOrientationFreeCamera;
  75125. }(BABYLON.DeviceOrientationCamera));
  75126. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  75127. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  75128. __extends(VRDeviceOrientationGamepadCamera, _super);
  75129. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75130. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75131. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75132. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  75133. _this.inputs.addGamepad();
  75134. return _this;
  75135. }
  75136. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  75137. return "VRDeviceOrientationGamepadCamera";
  75138. };
  75139. return VRDeviceOrientationGamepadCamera;
  75140. }(VRDeviceOrientationFreeCamera));
  75141. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  75142. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  75143. __extends(VRDeviceOrientationArcRotateCamera, _super);
  75144. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  75145. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75146. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75147. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75148. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75149. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75150. _this.inputs.addVRDeviceOrientation();
  75151. return _this;
  75152. }
  75153. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  75154. return "VRDeviceOrientationArcRotateCamera";
  75155. };
  75156. return VRDeviceOrientationArcRotateCamera;
  75157. }(BABYLON.ArcRotateCamera));
  75158. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  75159. })(BABYLON || (BABYLON = {}));
  75160. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  75161. var BABYLON;
  75162. (function (BABYLON) {
  75163. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  75164. __extends(AnaglyphFreeCamera, _super);
  75165. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  75166. var _this = _super.call(this, name, position, scene) || this;
  75167. _this.interaxialDistance = interaxialDistance;
  75168. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75169. return _this;
  75170. }
  75171. AnaglyphFreeCamera.prototype.getClassName = function () {
  75172. return "AnaglyphFreeCamera";
  75173. };
  75174. return AnaglyphFreeCamera;
  75175. }(BABYLON.FreeCamera));
  75176. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  75177. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  75178. __extends(AnaglyphArcRotateCamera, _super);
  75179. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  75180. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75181. _this.interaxialDistance = interaxialDistance;
  75182. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75183. return _this;
  75184. }
  75185. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  75186. return "AnaglyphArcRotateCamera";
  75187. };
  75188. return AnaglyphArcRotateCamera;
  75189. }(BABYLON.ArcRotateCamera));
  75190. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  75191. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  75192. __extends(AnaglyphGamepadCamera, _super);
  75193. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  75194. var _this = _super.call(this, name, position, scene) || this;
  75195. _this.interaxialDistance = interaxialDistance;
  75196. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75197. return _this;
  75198. }
  75199. AnaglyphGamepadCamera.prototype.getClassName = function () {
  75200. return "AnaglyphGamepadCamera";
  75201. };
  75202. return AnaglyphGamepadCamera;
  75203. }(BABYLON.GamepadCamera));
  75204. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  75205. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  75206. __extends(AnaglyphUniversalCamera, _super);
  75207. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  75208. var _this = _super.call(this, name, position, scene) || this;
  75209. _this.interaxialDistance = interaxialDistance;
  75210. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75211. return _this;
  75212. }
  75213. AnaglyphUniversalCamera.prototype.getClassName = function () {
  75214. return "AnaglyphUniversalCamera";
  75215. };
  75216. return AnaglyphUniversalCamera;
  75217. }(BABYLON.UniversalCamera));
  75218. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  75219. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  75220. __extends(StereoscopicFreeCamera, _super);
  75221. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75222. var _this = _super.call(this, name, position, scene) || this;
  75223. _this.interaxialDistance = interaxialDistance;
  75224. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75225. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75226. return _this;
  75227. }
  75228. StereoscopicFreeCamera.prototype.getClassName = function () {
  75229. return "StereoscopicFreeCamera";
  75230. };
  75231. return StereoscopicFreeCamera;
  75232. }(BABYLON.FreeCamera));
  75233. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  75234. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  75235. __extends(StereoscopicArcRotateCamera, _super);
  75236. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  75237. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75238. _this.interaxialDistance = interaxialDistance;
  75239. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75240. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75241. return _this;
  75242. }
  75243. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  75244. return "StereoscopicArcRotateCamera";
  75245. };
  75246. return StereoscopicArcRotateCamera;
  75247. }(BABYLON.ArcRotateCamera));
  75248. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  75249. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  75250. __extends(StereoscopicGamepadCamera, _super);
  75251. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75252. var _this = _super.call(this, name, position, scene) || this;
  75253. _this.interaxialDistance = interaxialDistance;
  75254. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75255. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75256. return _this;
  75257. }
  75258. StereoscopicGamepadCamera.prototype.getClassName = function () {
  75259. return "StereoscopicGamepadCamera";
  75260. };
  75261. return StereoscopicGamepadCamera;
  75262. }(BABYLON.GamepadCamera));
  75263. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  75264. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  75265. __extends(StereoscopicUniversalCamera, _super);
  75266. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75267. var _this = _super.call(this, name, position, scene) || this;
  75268. _this.interaxialDistance = interaxialDistance;
  75269. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75270. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75271. return _this;
  75272. }
  75273. StereoscopicUniversalCamera.prototype.getClassName = function () {
  75274. return "StereoscopicUniversalCamera";
  75275. };
  75276. return StereoscopicUniversalCamera;
  75277. }(BABYLON.UniversalCamera));
  75278. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  75279. })(BABYLON || (BABYLON = {}));
  75280. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  75281. var BABYLON;
  75282. (function (BABYLON) {
  75283. /**
  75284. * Helps to quickly add VR support to an existing scene.
  75285. * See http://doc.babylonjs.com/how_to/webvr_helper
  75286. */
  75287. var VRExperienceHelper = /** @class */ (function () {
  75288. /**
  75289. * Instantiates a VRExperienceHelper.
  75290. * Helps to quickly add VR support to an existing scene.
  75291. * @param scene The scene the VRExperienceHelper belongs to.
  75292. * @param webVROptions Options to modify the vr experience helper's behavior.
  75293. */
  75294. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  75295. if (webVROptions === void 0) { webVROptions = {}; }
  75296. var _this = this;
  75297. this.webVROptions = webVROptions;
  75298. // Can the system support WebVR, even if a headset isn't plugged in?
  75299. this._webVRsupported = false;
  75300. // If WebVR is supported, is a headset plugged in and are we ready to present?
  75301. this._webVRready = false;
  75302. // Are we waiting for the requestPresent callback to complete?
  75303. this._webVRrequesting = false;
  75304. // Are we presenting to the headset right now?
  75305. this._webVRpresenting = false;
  75306. // Are we presenting in the fullscreen fallback?
  75307. this._fullscreenVRpresenting = false;
  75308. /**
  75309. * Observable raised when entering VR.
  75310. */
  75311. this.onEnteringVRObservable = new BABYLON.Observable();
  75312. /**
  75313. * Observable raised when exiting VR.
  75314. */
  75315. this.onExitingVRObservable = new BABYLON.Observable();
  75316. /**
  75317. * Observable raised when controller mesh is loaded.
  75318. */
  75319. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75320. this._useCustomVRButton = false;
  75321. this._teleportationRequested = false;
  75322. this._teleportationEnabledOnLeftController = false;
  75323. this._teleportationEnabledOnRightController = false;
  75324. this._interactionsEnabledOnLeftController = false;
  75325. this._interactionsEnabledOnRightController = false;
  75326. this._leftControllerReady = false;
  75327. this._rightControllerReady = false;
  75328. this._floorMeshesCollection = [];
  75329. this._teleportationAllowed = false;
  75330. this._rotationAllowed = true;
  75331. this._teleportationRequestInitiated = false;
  75332. this._teleportationBackRequestInitiated = false;
  75333. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  75334. this._rotationRightAsked = false;
  75335. this._rotationLeftAsked = false;
  75336. this._isDefaultTeleportationTarget = true;
  75337. this._teleportationFillColor = "#444444";
  75338. this._teleportationBorderColor = "#FFFFFF";
  75339. this._rotationAngle = 0;
  75340. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  75341. this._padSensibilityUp = 0.65;
  75342. this._padSensibilityDown = 0.35;
  75343. /**
  75344. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  75345. */
  75346. this.onNewMeshSelected = new BABYLON.Observable();
  75347. /**
  75348. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  75349. */
  75350. this.onNewMeshPicked = new BABYLON.Observable();
  75351. /**
  75352. * Observable raised before camera teleportation
  75353. */
  75354. this.onBeforeCameraTeleport = new BABYLON.Observable();
  75355. /**
  75356. * Observable raised after camera teleportation
  75357. */
  75358. this.onAfterCameraTeleport = new BABYLON.Observable();
  75359. /**
  75360. * Observable raised when current selected mesh gets unselected
  75361. */
  75362. this.onSelectedMeshUnselected = new BABYLON.Observable();
  75363. /**
  75364. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  75365. */
  75366. this.teleportationEnabled = true;
  75367. this._pointerDownOnMeshAsked = false;
  75368. this._isActionableMesh = false;
  75369. this._teleportationInitialized = false;
  75370. this._interactionsEnabled = false;
  75371. this._interactionsRequested = false;
  75372. this._displayGaze = true;
  75373. this._displayLaserPointer = true;
  75374. this._dpadPressed = true;
  75375. this._onResize = function () {
  75376. _this.moveButtonToBottomRight();
  75377. if (_this._fullscreenVRpresenting && _this._webVRready) {
  75378. _this.exitVR();
  75379. }
  75380. };
  75381. this._onFullscreenChange = function () {
  75382. if (document.fullscreen !== undefined) {
  75383. _this._fullscreenVRpresenting = document.fullscreen;
  75384. }
  75385. else if (document.mozFullScreen !== undefined) {
  75386. _this._fullscreenVRpresenting = document.mozFullScreen;
  75387. }
  75388. else if (document.webkitIsFullScreen !== undefined) {
  75389. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  75390. }
  75391. else if (document.msIsFullScreen !== undefined) {
  75392. _this._fullscreenVRpresenting = document.msIsFullScreen;
  75393. }
  75394. if (!_this._fullscreenVRpresenting && _this._canvas) {
  75395. _this.exitVR();
  75396. if (!_this._useCustomVRButton) {
  75397. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  75398. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  75399. }
  75400. }
  75401. };
  75402. this.beforeRender = function () {
  75403. _this._castRayAndSelectObject();
  75404. };
  75405. this._onNewGamepadConnected = function (gamepad) {
  75406. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75407. if (gamepad.leftStick) {
  75408. gamepad.onleftstickchanged(function (stickValues) {
  75409. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  75410. // Listening to classic/xbox gamepad only if no VR controller is active
  75411. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  75412. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  75413. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  75414. _this._checkTeleportWithRay(stickValues);
  75415. _this._checkTeleportBackwards(stickValues);
  75416. }
  75417. }
  75418. });
  75419. }
  75420. if (gamepad.rightStick) {
  75421. gamepad.onrightstickchanged(function (stickValues) {
  75422. if (_this._teleportationInitialized) {
  75423. _this._checkRotate(stickValues);
  75424. }
  75425. });
  75426. }
  75427. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  75428. gamepad.onbuttondown(function (buttonPressed) {
  75429. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75430. _this._selectionPointerDown();
  75431. }
  75432. });
  75433. gamepad.onbuttonup(function (buttonPressed) {
  75434. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75435. _this._selectionPointerUp();
  75436. }
  75437. });
  75438. }
  75439. }
  75440. else {
  75441. var webVRController = gamepad;
  75442. _this._tryEnableInteractionOnController(webVRController);
  75443. }
  75444. };
  75445. // 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
  75446. this._tryEnableInteractionOnController = function (webVRController) {
  75447. if (webVRController.hand === "left") {
  75448. _this._leftControllerReady = true;
  75449. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  75450. _this._enableInteractionOnController(webVRController);
  75451. }
  75452. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  75453. _this._enableTeleportationOnController(webVRController);
  75454. }
  75455. }
  75456. if (webVRController.hand === "right") {
  75457. _this._rightControllerReady = true;
  75458. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  75459. _this._enableInteractionOnController(webVRController);
  75460. }
  75461. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  75462. _this._enableTeleportationOnController(webVRController);
  75463. }
  75464. }
  75465. };
  75466. this._onNewGamepadDisconnected = function (gamepad) {
  75467. if (gamepad instanceof BABYLON.WebVRController) {
  75468. if (gamepad.hand === "left") {
  75469. _this._interactionsEnabledOnLeftController = false;
  75470. _this._teleportationEnabledOnLeftController = false;
  75471. _this._leftControllerReady = false;
  75472. if (_this._leftLaserPointer) {
  75473. _this._leftLaserPointer.dispose();
  75474. }
  75475. }
  75476. if (gamepad.hand === "right") {
  75477. _this._interactionsEnabledOnRightController = false;
  75478. _this._teleportationEnabledOnRightController = false;
  75479. _this._rightControllerReady = false;
  75480. if (_this._rightLaserPointer) {
  75481. _this._rightLaserPointer.dispose();
  75482. }
  75483. }
  75484. }
  75485. };
  75486. this._workingVector = BABYLON.Vector3.Zero();
  75487. this._workingQuaternion = BABYLON.Quaternion.Identity();
  75488. this._workingMatrix = BABYLON.Matrix.Identity();
  75489. this._scene = scene;
  75490. this._canvas = scene.getEngine().getRenderingCanvas();
  75491. // Parse options
  75492. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  75493. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  75494. }
  75495. if (webVROptions.createDeviceOrientationCamera === undefined) {
  75496. webVROptions.createDeviceOrientationCamera = true;
  75497. }
  75498. if (webVROptions.defaultHeight === undefined) {
  75499. webVROptions.defaultHeight = 1.7;
  75500. }
  75501. if (webVROptions.useCustomVRButton) {
  75502. this._useCustomVRButton = true;
  75503. if (webVROptions.customVRButton) {
  75504. this._btnVR = webVROptions.customVRButton;
  75505. }
  75506. }
  75507. if (webVROptions.rayLength) {
  75508. this._rayLength = webVROptions.rayLength;
  75509. }
  75510. this._defaultHeight = webVROptions.defaultHeight;
  75511. // Set position
  75512. if (this._scene.activeCamera) {
  75513. this._position = this._scene.activeCamera.position.clone();
  75514. }
  75515. else {
  75516. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  75517. }
  75518. // Set non-vr camera
  75519. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  75520. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  75521. // Copy data from existing camera
  75522. if (this._scene.activeCamera) {
  75523. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  75524. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  75525. // Set rotation from previous camera
  75526. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  75527. var targetCamera = this._scene.activeCamera;
  75528. if (targetCamera.rotationQuaternion) {
  75529. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  75530. }
  75531. else {
  75532. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  75533. }
  75534. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  75535. }
  75536. }
  75537. this._scene.activeCamera = this._deviceOrientationCamera;
  75538. if (this._canvas) {
  75539. this._scene.activeCamera.attachControl(this._canvas);
  75540. }
  75541. }
  75542. else {
  75543. this._existingCamera = this._scene.activeCamera;
  75544. }
  75545. // Create VR cameras
  75546. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75547. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75548. }
  75549. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75550. this._webVRCamera.useStandingMatrix();
  75551. // Create default button
  75552. if (!this._useCustomVRButton) {
  75553. this._btnVR = document.createElement("BUTTON");
  75554. this._btnVR.className = "babylonVRicon";
  75555. this._btnVR.id = "babylonVRiconbtn";
  75556. this._btnVR.title = "Click to switch to VR";
  75557. 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) }";
  75558. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75559. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75560. // css += ".babylonVRicon.vrdisplaysupported { }";
  75561. // css += ".babylonVRicon.vrdisplayready { }";
  75562. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75563. var style = document.createElement('style');
  75564. style.appendChild(document.createTextNode(css));
  75565. document.getElementsByTagName('head')[0].appendChild(style);
  75566. this.moveButtonToBottomRight();
  75567. }
  75568. // VR button click event
  75569. if (this._btnVR) {
  75570. this._btnVR.addEventListener("click", function () {
  75571. if (!_this.isInVRMode) {
  75572. _this.enterVR();
  75573. }
  75574. else {
  75575. _this.exitVR();
  75576. }
  75577. });
  75578. }
  75579. // Window events
  75580. window.addEventListener("resize", this._onResize);
  75581. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75582. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75583. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75584. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75585. // Display vr button when headset is connected
  75586. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75587. this.displayVRButton();
  75588. }
  75589. else {
  75590. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75591. if (e.vrDisplay) {
  75592. _this.displayVRButton();
  75593. }
  75594. });
  75595. }
  75596. // Exiting VR mode using 'ESC' key on desktop
  75597. this._onKeyDown = function (event) {
  75598. if (event.keyCode === 27 && _this.isInVRMode) {
  75599. _this.exitVR();
  75600. }
  75601. };
  75602. document.addEventListener("keydown", this._onKeyDown);
  75603. // Exiting VR mode double tapping the touch screen
  75604. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75605. if (_this.isInVRMode) {
  75606. _this.exitVR();
  75607. if (_this._fullscreenVRpresenting) {
  75608. _this._scene.getEngine().switchFullscreen(true);
  75609. }
  75610. }
  75611. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75612. // Listen for WebVR display changes
  75613. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75614. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75615. this._onVRRequestPresentStart = function () {
  75616. _this._webVRrequesting = true;
  75617. _this.updateButtonVisibility();
  75618. };
  75619. this._onVRRequestPresentComplete = function (success) {
  75620. _this._webVRrequesting = false;
  75621. _this.updateButtonVisibility();
  75622. };
  75623. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75624. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75625. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75626. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75627. scene.onDisposeObservable.add(function () {
  75628. _this.dispose();
  75629. });
  75630. // Gamepad connection events
  75631. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75632. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75633. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75634. this.updateButtonVisibility();
  75635. //create easing functions
  75636. this._circleEase = new BABYLON.CircleEase();
  75637. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75638. }
  75639. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75640. /** Return this.onEnteringVRObservable
  75641. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75642. */
  75643. get: function () {
  75644. return this.onEnteringVRObservable;
  75645. },
  75646. enumerable: true,
  75647. configurable: true
  75648. });
  75649. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75650. /** Return this.onExitingVRObservable
  75651. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75652. */
  75653. get: function () {
  75654. return this.onExitingVRObservable;
  75655. },
  75656. enumerable: true,
  75657. configurable: true
  75658. });
  75659. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75660. /** Return this.onControllerMeshLoadedObservable
  75661. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75662. */
  75663. get: function () {
  75664. return this.onControllerMeshLoadedObservable;
  75665. },
  75666. enumerable: true,
  75667. configurable: true
  75668. });
  75669. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  75670. /**
  75671. * The mesh used to display where the user is going to teleport.
  75672. */
  75673. get: function () {
  75674. return this._teleportationTarget;
  75675. },
  75676. /**
  75677. * Sets the mesh to be used to display where the user is going to teleport.
  75678. */
  75679. set: function (value) {
  75680. if (value) {
  75681. value.name = "teleportationTarget";
  75682. this._isDefaultTeleportationTarget = false;
  75683. this._teleportationTarget = value;
  75684. }
  75685. },
  75686. enumerable: true,
  75687. configurable: true
  75688. });
  75689. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  75690. /**
  75691. * If the ray of the gaze should be displayed.
  75692. */
  75693. get: function () {
  75694. return this._displayGaze;
  75695. },
  75696. /**
  75697. * Sets if the ray of the gaze should be displayed.
  75698. */
  75699. set: function (value) {
  75700. this._displayGaze = value;
  75701. if (!value) {
  75702. this._gazeTracker.isVisible = false;
  75703. }
  75704. },
  75705. enumerable: true,
  75706. configurable: true
  75707. });
  75708. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  75709. /**
  75710. * If the ray of the LaserPointer should be displayed.
  75711. */
  75712. get: function () {
  75713. return this._displayLaserPointer;
  75714. },
  75715. /**
  75716. * Sets if the ray of the LaserPointer should be displayed.
  75717. */
  75718. set: function (value) {
  75719. this._displayLaserPointer = value;
  75720. if (!value) {
  75721. if (this._rightLaserPointer) {
  75722. this._rightLaserPointer.isVisible = false;
  75723. }
  75724. if (this._leftLaserPointer) {
  75725. this._leftLaserPointer.isVisible = false;
  75726. }
  75727. }
  75728. else {
  75729. if (this._rightLaserPointer) {
  75730. this._rightLaserPointer.isVisible = true;
  75731. }
  75732. else if (this._leftLaserPointer) {
  75733. this._leftLaserPointer.isVisible = true;
  75734. }
  75735. }
  75736. },
  75737. enumerable: true,
  75738. configurable: true
  75739. });
  75740. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  75741. /**
  75742. * The deviceOrientationCamera used as the camera when not in VR.
  75743. */
  75744. get: function () {
  75745. return this._deviceOrientationCamera;
  75746. },
  75747. enumerable: true,
  75748. configurable: true
  75749. });
  75750. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  75751. /**
  75752. * Based on the current WebVR support, returns the current VR camera used.
  75753. */
  75754. get: function () {
  75755. if (this._webVRready) {
  75756. return this._webVRCamera;
  75757. }
  75758. else {
  75759. return this._scene.activeCamera;
  75760. }
  75761. },
  75762. enumerable: true,
  75763. configurable: true
  75764. });
  75765. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  75766. /**
  75767. * The webVRCamera which is used when in VR.
  75768. */
  75769. get: function () {
  75770. return this._webVRCamera;
  75771. },
  75772. enumerable: true,
  75773. configurable: true
  75774. });
  75775. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  75776. /**
  75777. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  75778. */
  75779. get: function () {
  75780. return this._vrDeviceOrientationCamera;
  75781. },
  75782. enumerable: true,
  75783. configurable: true
  75784. });
  75785. // Raised when one of the controller has loaded successfully its associated default mesh
  75786. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  75787. this._tryEnableInteractionOnController(webVRController);
  75788. try {
  75789. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  75790. }
  75791. catch (err) {
  75792. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  75793. }
  75794. };
  75795. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  75796. /**
  75797. * Gets a value indicating if we are currently in VR mode.
  75798. */
  75799. get: function () {
  75800. return this._webVRpresenting || this._fullscreenVRpresenting;
  75801. },
  75802. enumerable: true,
  75803. configurable: true
  75804. });
  75805. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  75806. var vrDisplay = this._scene.getEngine().getVRDevice();
  75807. if (vrDisplay) {
  75808. var wasPresenting = this._webVRpresenting;
  75809. // A VR display is connected
  75810. this._webVRpresenting = vrDisplay.isPresenting;
  75811. if (wasPresenting && !this._webVRpresenting)
  75812. this.exitVR();
  75813. }
  75814. else {
  75815. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  75816. }
  75817. this.updateButtonVisibility();
  75818. };
  75819. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  75820. this._webVRsupported = eventArgs.vrSupported;
  75821. this._webVRready = !!eventArgs.vrDisplay;
  75822. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  75823. this.updateButtonVisibility();
  75824. };
  75825. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  75826. if (this._canvas && !this._useCustomVRButton) {
  75827. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  75828. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  75829. }
  75830. };
  75831. VRExperienceHelper.prototype.displayVRButton = function () {
  75832. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  75833. document.body.appendChild(this._btnVR);
  75834. this._btnVRDisplayed = true;
  75835. }
  75836. };
  75837. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  75838. if (!this._btnVR || this._useCustomVRButton) {
  75839. return;
  75840. }
  75841. this._btnVR.className = "babylonVRicon";
  75842. if (this.isInVRMode) {
  75843. this._btnVR.className += " vrdisplaypresenting";
  75844. }
  75845. else {
  75846. if (this._webVRready)
  75847. this._btnVR.className += " vrdisplayready";
  75848. if (this._webVRsupported)
  75849. this._btnVR.className += " vrdisplaysupported";
  75850. if (this._webVRrequesting)
  75851. this._btnVR.className += " vrdisplayrequesting";
  75852. }
  75853. };
  75854. /**
  75855. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  75856. * Otherwise, will use the fullscreen API.
  75857. */
  75858. VRExperienceHelper.prototype.enterVR = function () {
  75859. if (this.onEnteringVRObservable) {
  75860. try {
  75861. this.onEnteringVRObservable.notifyObservers(this);
  75862. }
  75863. catch (err) {
  75864. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  75865. }
  75866. }
  75867. if (this._scene.activeCamera) {
  75868. this._position = this._scene.activeCamera.position.clone();
  75869. // make sure that we return to the last active camera
  75870. this._existingCamera = this._scene.activeCamera;
  75871. }
  75872. if (this._webVRrequesting)
  75873. return;
  75874. // If WebVR is supported and a headset is connected
  75875. if (this._webVRready) {
  75876. if (!this._webVRpresenting) {
  75877. this._webVRCamera.position = this._position;
  75878. this._scene.activeCamera = this._webVRCamera;
  75879. }
  75880. }
  75881. else if (this._vrDeviceOrientationCamera) {
  75882. this._vrDeviceOrientationCamera.position = this._position;
  75883. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  75884. this._scene.getEngine().switchFullscreen(true);
  75885. this.updateButtonVisibility();
  75886. }
  75887. if (this._scene.activeCamera && this._canvas) {
  75888. this._scene.activeCamera.attachControl(this._canvas);
  75889. }
  75890. if (this._interactionsEnabled) {
  75891. this._scene.registerBeforeRender(this.beforeRender);
  75892. }
  75893. };
  75894. /**
  75895. * Attempt to exit VR, or fullscreen.
  75896. */
  75897. VRExperienceHelper.prototype.exitVR = function () {
  75898. if (this.onExitingVRObservable) {
  75899. try {
  75900. this.onExitingVRObservable.notifyObservers(this);
  75901. }
  75902. catch (err) {
  75903. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  75904. }
  75905. }
  75906. if (this._webVRpresenting) {
  75907. this._scene.getEngine().disableVR();
  75908. }
  75909. if (this._scene.activeCamera) {
  75910. this._position = this._scene.activeCamera.position.clone();
  75911. }
  75912. if (this._deviceOrientationCamera) {
  75913. this._deviceOrientationCamera.position = this._position;
  75914. this._scene.activeCamera = this._deviceOrientationCamera;
  75915. if (this._canvas) {
  75916. this._scene.activeCamera.attachControl(this._canvas);
  75917. }
  75918. }
  75919. else if (this._existingCamera) {
  75920. this._existingCamera.position = this._position;
  75921. this._scene.activeCamera = this._existingCamera;
  75922. }
  75923. this.updateButtonVisibility();
  75924. if (this._interactionsEnabled) {
  75925. this._scene.unregisterBeforeRender(this.beforeRender);
  75926. }
  75927. };
  75928. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  75929. /**
  75930. * The position of the vr experience helper.
  75931. */
  75932. get: function () {
  75933. return this._position;
  75934. },
  75935. /**
  75936. * Sets the position of the vr experience helper.
  75937. */
  75938. set: function (value) {
  75939. this._position = value;
  75940. if (this._scene.activeCamera) {
  75941. this._scene.activeCamera.position = value;
  75942. }
  75943. },
  75944. enumerable: true,
  75945. configurable: true
  75946. });
  75947. /**
  75948. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  75949. */
  75950. VRExperienceHelper.prototype.enableInteractions = function () {
  75951. var _this = this;
  75952. if (!this._interactionsEnabled) {
  75953. this._interactionsRequested = true;
  75954. if (this._leftControllerReady && this._webVRCamera.leftController) {
  75955. this._enableInteractionOnController(this._webVRCamera.leftController);
  75956. }
  75957. if (this._rightControllerReady && this._webVRCamera.rightController) {
  75958. this._enableInteractionOnController(this._webVRCamera.rightController);
  75959. }
  75960. this._createGazeTracker();
  75961. this.raySelectionPredicate = function (mesh) {
  75962. return mesh.isVisible;
  75963. };
  75964. this.meshSelectionPredicate = function (mesh) {
  75965. return true;
  75966. };
  75967. this._raySelectionPredicate = function (mesh) {
  75968. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  75969. && mesh.name.indexOf("teleportationTarget") === -1
  75970. && mesh.name.indexOf("torusTeleportation") === -1
  75971. && mesh.name.indexOf("laserPointer") === -1)) {
  75972. return _this.raySelectionPredicate(mesh);
  75973. }
  75974. return false;
  75975. };
  75976. this._interactionsEnabled = true;
  75977. }
  75978. };
  75979. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  75980. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  75981. if (this._floorMeshesCollection[i].id === mesh.id) {
  75982. return true;
  75983. }
  75984. }
  75985. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  75986. return true;
  75987. }
  75988. return false;
  75989. };
  75990. /**
  75991. * Adds a floor mesh to be used for teleportation.
  75992. * @param floorMesh the mesh to be used for teleportation.
  75993. */
  75994. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  75995. if (!this._floorMeshesCollection) {
  75996. return;
  75997. }
  75998. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  75999. return;
  76000. }
  76001. this._floorMeshesCollection.push(floorMesh);
  76002. };
  76003. /**
  76004. * Removes a floor mesh from being used for teleportation.
  76005. * @param floorMesh the mesh to be removed.
  76006. */
  76007. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  76008. if (!this._floorMeshesCollection) {
  76009. return;
  76010. }
  76011. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  76012. if (meshIndex !== -1) {
  76013. this._floorMeshesCollection.splice(meshIndex, 1);
  76014. }
  76015. };
  76016. /**
  76017. * Enables interactions and teleportation using the VR controllers and gaze.
  76018. * @param vrTeleportationOptions options to modify teleportation behavior.
  76019. */
  76020. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  76021. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  76022. if (!this._teleportationInitialized) {
  76023. this._teleportationRequested = true;
  76024. this.enableInteractions();
  76025. if (vrTeleportationOptions.floorMeshName) {
  76026. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  76027. }
  76028. if (vrTeleportationOptions.floorMeshes) {
  76029. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  76030. }
  76031. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76032. this._enableTeleportationOnController(this._webVRCamera.leftController);
  76033. }
  76034. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76035. this._enableTeleportationOnController(this._webVRCamera.rightController);
  76036. }
  76037. // Creates an image processing post process for the vignette not relying
  76038. // on the main scene configuration for image processing to reduce setup and spaces
  76039. // (gamma/linear) conflicts.
  76040. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  76041. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76042. imageProcessingConfiguration.vignetteEnabled = true;
  76043. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  76044. this._webVRCamera.detachPostProcess(this._postProcessMove);
  76045. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  76046. this._teleportationInitialized = true;
  76047. if (this._isDefaultTeleportationTarget) {
  76048. this._createTeleportationCircles();
  76049. }
  76050. }
  76051. };
  76052. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  76053. var _this = this;
  76054. var controllerMesh = webVRController.mesh;
  76055. if (controllerMesh) {
  76056. var makeNotPick = function (root) {
  76057. root.name += " laserPointer";
  76058. root.getChildMeshes().forEach(function (c) {
  76059. makeNotPick(c);
  76060. });
  76061. };
  76062. makeNotPick(controllerMesh);
  76063. var childMeshes = controllerMesh.getChildMeshes();
  76064. for (var i = 0; i < childMeshes.length; i++) {
  76065. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  76066. controllerMesh = childMeshes[i];
  76067. break;
  76068. }
  76069. }
  76070. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  76071. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  76072. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76073. laserPointerMaterial.alpha = 0.6;
  76074. laserPointer.material = laserPointerMaterial;
  76075. laserPointer.rotation.x = Math.PI / 2;
  76076. laserPointer.parent = controllerMesh;
  76077. laserPointer.position.z = -0.5;
  76078. laserPointer.isVisible = false;
  76079. if (webVRController.hand === "left") {
  76080. this._leftLaserPointer = laserPointer;
  76081. this._interactionsEnabledOnLeftController = true;
  76082. if (!this._rightLaserPointer) {
  76083. this._leftLaserPointer.isVisible = true;
  76084. }
  76085. }
  76086. else {
  76087. this._rightLaserPointer = laserPointer;
  76088. this._interactionsEnabledOnRightController = true;
  76089. if (!this._leftLaserPointer) {
  76090. this._rightLaserPointer.isVisible = true;
  76091. }
  76092. }
  76093. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  76094. // Enabling / disabling laserPointer
  76095. if (_this._displayLaserPointer && stateObject.value === 1) {
  76096. laserPointer.isVisible = !laserPointer.isVisible;
  76097. // Laser pointer can only be active on left or right, not both at the same time
  76098. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  76099. _this._rightLaserPointer.isVisible = false;
  76100. }
  76101. else if (_this._leftLaserPointer) {
  76102. _this._leftLaserPointer.isVisible = false;
  76103. }
  76104. }
  76105. });
  76106. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  76107. if (!_this._pointerDownOnMeshAsked) {
  76108. if (stateObject.value > _this._padSensibilityUp) {
  76109. _this._selectionPointerDown();
  76110. }
  76111. }
  76112. else if (stateObject.value < _this._padSensibilityDown) {
  76113. _this._selectionPointerUp();
  76114. }
  76115. });
  76116. }
  76117. };
  76118. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  76119. if (webVRController === void 0) { webVRController = null; }
  76120. if (!this._teleportationRequestInitiated) {
  76121. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  76122. if (webVRController) {
  76123. // If laser pointer wasn't enabled yet
  76124. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  76125. this._leftLaserPointer.isVisible = true;
  76126. if (this._rightLaserPointer) {
  76127. this._rightLaserPointer.isVisible = false;
  76128. }
  76129. }
  76130. else if (this._displayLaserPointer && this._rightLaserPointer) {
  76131. this._rightLaserPointer.isVisible = true;
  76132. if (this._leftLaserPointer) {
  76133. this._leftLaserPointer.isVisible = false;
  76134. }
  76135. }
  76136. }
  76137. this._teleportationRequestInitiated = true;
  76138. }
  76139. }
  76140. else {
  76141. // Listening to the proper controller values changes to confirm teleportation
  76142. if (webVRController == null
  76143. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  76144. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  76145. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  76146. if (this._teleportationAllowed) {
  76147. this._teleportationAllowed = false;
  76148. this._teleportCamera();
  76149. }
  76150. this._teleportationRequestInitiated = false;
  76151. }
  76152. }
  76153. }
  76154. };
  76155. VRExperienceHelper.prototype._selectionPointerDown = function () {
  76156. this._pointerDownOnMeshAsked = true;
  76157. if (this._currentMeshSelected && this._currentHit) {
  76158. this._scene.simulatePointerDown(this._currentHit);
  76159. }
  76160. };
  76161. VRExperienceHelper.prototype._selectionPointerUp = function () {
  76162. if (this._currentMeshSelected && this._currentHit) {
  76163. this._scene.simulatePointerUp(this._currentHit);
  76164. }
  76165. this._pointerDownOnMeshAsked = false;
  76166. };
  76167. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  76168. // Only rotate when user is not currently selecting a teleportation location
  76169. if (this._teleportationRequestInitiated) {
  76170. return;
  76171. }
  76172. if (!this._rotationLeftAsked) {
  76173. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  76174. this._rotationLeftAsked = true;
  76175. if (this._rotationAllowed) {
  76176. this._rotateCamera(false);
  76177. }
  76178. }
  76179. }
  76180. else {
  76181. if (stateObject.x > -this._padSensibilityDown) {
  76182. this._rotationLeftAsked = false;
  76183. }
  76184. }
  76185. if (!this._rotationRightAsked) {
  76186. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  76187. this._rotationRightAsked = true;
  76188. if (this._rotationAllowed) {
  76189. this._rotateCamera(true);
  76190. }
  76191. }
  76192. }
  76193. else {
  76194. if (stateObject.x < this._padSensibilityDown) {
  76195. this._rotationRightAsked = false;
  76196. }
  76197. }
  76198. };
  76199. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  76200. // Only teleport backwards when user is not currently selecting a teleportation location
  76201. if (this._teleportationRequestInitiated) {
  76202. return;
  76203. }
  76204. // Teleport backwards
  76205. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  76206. if (!this._teleportationBackRequestInitiated) {
  76207. if (!this.currentVRCamera) {
  76208. return;
  76209. }
  76210. // Get rotation and position of the current camera
  76211. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  76212. var position = this.currentVRCamera.position;
  76213. // If the camera has device position, use that instead
  76214. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  76215. rotation = this.currentVRCamera.deviceRotationQuaternion;
  76216. position = this.currentVRCamera.devicePosition;
  76217. }
  76218. // Get matrix with only the y rotation of the device rotation
  76219. rotation.toEulerAnglesToRef(this._workingVector);
  76220. this._workingVector.z = 0;
  76221. this._workingVector.x = 0;
  76222. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  76223. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  76224. // Rotate backwards ray by device rotation to cast at the ground behind the user
  76225. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  76226. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  76227. var ray = new BABYLON.Ray(position, this._workingVector);
  76228. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76229. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  76230. this._teleportCamera(hit.pickedPoint);
  76231. }
  76232. this._teleportationBackRequestInitiated = true;
  76233. }
  76234. }
  76235. else {
  76236. this._teleportationBackRequestInitiated = false;
  76237. }
  76238. };
  76239. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  76240. var _this = this;
  76241. var controllerMesh = webVRController.mesh;
  76242. if (controllerMesh) {
  76243. if (webVRController.hand === "left") {
  76244. if (!this._interactionsEnabledOnLeftController) {
  76245. this._enableInteractionOnController(webVRController);
  76246. }
  76247. this._teleportationEnabledOnLeftController = true;
  76248. }
  76249. else {
  76250. if (!this._interactionsEnabledOnRightController) {
  76251. this._enableInteractionOnController(webVRController);
  76252. }
  76253. this._teleportationEnabledOnRightController = true;
  76254. }
  76255. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76256. this._dpadPressed = false;
  76257. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  76258. _this._dpadPressed = stateObject.pressed;
  76259. if (!_this._dpadPressed) {
  76260. _this._rotationLeftAsked = false;
  76261. _this._rotationRightAsked = false;
  76262. _this._teleportationBackRequestInitiated = false;
  76263. }
  76264. });
  76265. }
  76266. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  76267. if (_this.teleportationEnabled) {
  76268. _this._checkTeleportBackwards(stateObject);
  76269. _this._checkTeleportWithRay(stateObject, webVRController);
  76270. }
  76271. _this._checkRotate(stateObject);
  76272. });
  76273. }
  76274. };
  76275. // Gaze support used to point to teleport or to interact with an object
  76276. VRExperienceHelper.prototype._createGazeTracker = function () {
  76277. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  76278. this._gazeTracker.bakeCurrentTransformIntoVertices();
  76279. this._gazeTracker.isPickable = false;
  76280. this._gazeTracker.isVisible = false;
  76281. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  76282. targetMat.specularColor = BABYLON.Color3.Black();
  76283. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76284. targetMat.backFaceCulling = false;
  76285. this._gazeTracker.material = targetMat;
  76286. };
  76287. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  76288. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  76289. this._teleportationTarget.isPickable = false;
  76290. var length = 512;
  76291. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  76292. dynamicTexture.hasAlpha = true;
  76293. var context = dynamicTexture.getContext();
  76294. var centerX = length / 2;
  76295. var centerY = length / 2;
  76296. var radius = 200;
  76297. context.beginPath();
  76298. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  76299. context.fillStyle = this._teleportationFillColor;
  76300. context.fill();
  76301. context.lineWidth = 10;
  76302. context.strokeStyle = this._teleportationBorderColor;
  76303. context.stroke();
  76304. context.closePath();
  76305. dynamicTexture.update();
  76306. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  76307. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  76308. this._teleportationTarget.material = teleportationCircleMaterial;
  76309. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  76310. torus.isPickable = false;
  76311. torus.parent = this._teleportationTarget;
  76312. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76313. var keys = [];
  76314. keys.push({
  76315. frame: 0,
  76316. value: 0
  76317. });
  76318. keys.push({
  76319. frame: 30,
  76320. value: 0.4
  76321. });
  76322. keys.push({
  76323. frame: 60,
  76324. value: 0
  76325. });
  76326. animationInnerCircle.setKeys(keys);
  76327. var easingFunction = new BABYLON.SineEase();
  76328. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76329. animationInnerCircle.setEasingFunction(easingFunction);
  76330. torus.animations = [];
  76331. torus.animations.push(animationInnerCircle);
  76332. this._scene.beginAnimation(torus, 0, 60, true);
  76333. this._hideTeleportationTarget();
  76334. };
  76335. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  76336. if (this._teleportationInitialized) {
  76337. this._teleportationTarget.isVisible = true;
  76338. if (this._isDefaultTeleportationTarget) {
  76339. this._teleportationTarget.getChildren()[0].isVisible = true;
  76340. }
  76341. }
  76342. };
  76343. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  76344. if (this._teleportationInitialized) {
  76345. this._teleportationTarget.isVisible = false;
  76346. if (this._isDefaultTeleportationTarget) {
  76347. this._teleportationTarget.getChildren()[0].isVisible = false;
  76348. }
  76349. }
  76350. };
  76351. VRExperienceHelper.prototype._rotateCamera = function (right) {
  76352. var _this = this;
  76353. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76354. return;
  76355. }
  76356. if (right) {
  76357. this._rotationAngle++;
  76358. }
  76359. else {
  76360. this._rotationAngle--;
  76361. }
  76362. this.currentVRCamera.animations = [];
  76363. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  76364. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76365. var animationRotationKeys = [];
  76366. animationRotationKeys.push({
  76367. frame: 0,
  76368. value: this.currentVRCamera.rotationQuaternion
  76369. });
  76370. animationRotationKeys.push({
  76371. frame: 6,
  76372. value: target
  76373. });
  76374. animationRotation.setKeys(animationRotationKeys);
  76375. animationRotation.setEasingFunction(this._circleEase);
  76376. this.currentVRCamera.animations.push(animationRotation);
  76377. this._postProcessMove.animations = [];
  76378. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76379. var vignetteWeightKeys = [];
  76380. vignetteWeightKeys.push({
  76381. frame: 0,
  76382. value: 0
  76383. });
  76384. vignetteWeightKeys.push({
  76385. frame: 3,
  76386. value: 4
  76387. });
  76388. vignetteWeightKeys.push({
  76389. frame: 6,
  76390. value: 0
  76391. });
  76392. animationPP.setKeys(vignetteWeightKeys);
  76393. animationPP.setEasingFunction(this._circleEase);
  76394. this._postProcessMove.animations.push(animationPP);
  76395. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76396. var vignetteStretchKeys = [];
  76397. vignetteStretchKeys.push({
  76398. frame: 0,
  76399. value: 0
  76400. });
  76401. vignetteStretchKeys.push({
  76402. frame: 3,
  76403. value: 10
  76404. });
  76405. vignetteStretchKeys.push({
  76406. frame: 6,
  76407. value: 0
  76408. });
  76409. animationPP2.setKeys(vignetteStretchKeys);
  76410. animationPP2.setEasingFunction(this._circleEase);
  76411. this._postProcessMove.animations.push(animationPP2);
  76412. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76413. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76414. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76415. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  76416. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76417. });
  76418. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  76419. };
  76420. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  76421. if (hit.pickedPoint) {
  76422. this._teleportationAllowed = true;
  76423. if (this._teleportationRequestInitiated) {
  76424. this._displayTeleportationTarget();
  76425. }
  76426. else {
  76427. this._hideTeleportationTarget();
  76428. }
  76429. this._haloCenter.copyFrom(hit.pickedPoint);
  76430. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  76431. var pickNormal = hit.getNormal(true, false);
  76432. if (pickNormal) {
  76433. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76434. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76435. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  76436. }
  76437. this._teleportationTarget.position.y += 0.1;
  76438. }
  76439. };
  76440. VRExperienceHelper.prototype._teleportCamera = function (location) {
  76441. var _this = this;
  76442. if (location === void 0) { location = null; }
  76443. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76444. return;
  76445. }
  76446. if (!location) {
  76447. location = this._haloCenter;
  76448. }
  76449. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  76450. // offset of the headset from the anchor.
  76451. if (this.webVRCamera.leftCamera) {
  76452. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  76453. this._workingVector.subtractInPlace(this.webVRCamera.position);
  76454. location.subtractToRef(this._workingVector, this._workingVector);
  76455. }
  76456. else {
  76457. this._workingVector.copyFrom(location);
  76458. }
  76459. // Add height to account for user's height offset
  76460. if (this.isInVRMode) {
  76461. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  76462. }
  76463. else {
  76464. this._workingVector.y += this._defaultHeight;
  76465. }
  76466. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  76467. // Create animation from the camera's position to the new location
  76468. this.currentVRCamera.animations = [];
  76469. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76470. var animationCameraTeleportationKeys = [{
  76471. frame: 0,
  76472. value: this.currentVRCamera.position
  76473. },
  76474. {
  76475. frame: 11,
  76476. value: this._workingVector
  76477. }
  76478. ];
  76479. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  76480. animationCameraTeleportation.setEasingFunction(this._circleEase);
  76481. this.currentVRCamera.animations.push(animationCameraTeleportation);
  76482. this._postProcessMove.animations = [];
  76483. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76484. var vignetteWeightKeys = [];
  76485. vignetteWeightKeys.push({
  76486. frame: 0,
  76487. value: 0
  76488. });
  76489. vignetteWeightKeys.push({
  76490. frame: 5,
  76491. value: 8
  76492. });
  76493. vignetteWeightKeys.push({
  76494. frame: 11,
  76495. value: 0
  76496. });
  76497. animationPP.setKeys(vignetteWeightKeys);
  76498. this._postProcessMove.animations.push(animationPP);
  76499. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76500. var vignetteStretchKeys = [];
  76501. vignetteStretchKeys.push({
  76502. frame: 0,
  76503. value: 0
  76504. });
  76505. vignetteStretchKeys.push({
  76506. frame: 5,
  76507. value: 10
  76508. });
  76509. vignetteStretchKeys.push({
  76510. frame: 11,
  76511. value: 0
  76512. });
  76513. animationPP2.setKeys(vignetteStretchKeys);
  76514. this._postProcessMove.animations.push(animationPP2);
  76515. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76516. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76517. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76518. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  76519. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76520. });
  76521. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  76522. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  76523. });
  76524. };
  76525. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  76526. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76527. return;
  76528. }
  76529. var ray;
  76530. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  76531. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  76532. }
  76533. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  76534. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  76535. }
  76536. else {
  76537. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  76538. }
  76539. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76540. // Moving the gazeTracker on the mesh face targetted
  76541. if (hit && hit.pickedPoint) {
  76542. if (this._displayGaze) {
  76543. var multiplier = 1;
  76544. this._gazeTracker.isVisible = true;
  76545. if (this._isActionableMesh) {
  76546. multiplier = 3;
  76547. }
  76548. this._gazeTracker.scaling.x = hit.distance * multiplier;
  76549. this._gazeTracker.scaling.y = hit.distance * multiplier;
  76550. this._gazeTracker.scaling.z = hit.distance * multiplier;
  76551. var pickNormal = hit.getNormal();
  76552. // To avoid z-fighting
  76553. var deltaFighting = 0.002;
  76554. if (pickNormal) {
  76555. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76556. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76557. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  76558. }
  76559. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  76560. if (this._gazeTracker.position.x < 0) {
  76561. this._gazeTracker.position.x += deltaFighting;
  76562. }
  76563. else {
  76564. this._gazeTracker.position.x -= deltaFighting;
  76565. }
  76566. if (this._gazeTracker.position.y < 0) {
  76567. this._gazeTracker.position.y += deltaFighting;
  76568. }
  76569. else {
  76570. this._gazeTracker.position.y -= deltaFighting;
  76571. }
  76572. if (this._gazeTracker.position.z < 0) {
  76573. this._gazeTracker.position.z += deltaFighting;
  76574. }
  76575. else {
  76576. this._gazeTracker.position.z -= deltaFighting;
  76577. }
  76578. }
  76579. // Changing the size of the laser pointer based on the distance from the targetted point
  76580. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  76581. this._rightLaserPointer.scaling.y = hit.distance;
  76582. this._rightLaserPointer.position.z = -hit.distance / 2;
  76583. }
  76584. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  76585. this._leftLaserPointer.scaling.y = hit.distance;
  76586. this._leftLaserPointer.position.z = -hit.distance / 2;
  76587. }
  76588. }
  76589. else {
  76590. this._gazeTracker.isVisible = false;
  76591. }
  76592. if (hit && hit.pickedMesh) {
  76593. this._currentHit = hit;
  76594. if (this._pointerDownOnMeshAsked) {
  76595. this._scene.simulatePointerMove(this._currentHit);
  76596. }
  76597. // The object selected is the floor, we're in a teleportation scenario
  76598. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76599. // Moving the teleportation area to this targetted point
  76600. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76601. if (this._currentMeshSelected &&
  76602. !this._isTeleportationFloor(this._currentMeshSelected)) {
  76603. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76604. }
  76605. this._currentMeshSelected = null;
  76606. this._moveTeleportationSelectorTo(hit);
  76607. return;
  76608. }
  76609. // If not, we're in a selection scenario
  76610. this._hideTeleportationTarget();
  76611. this._teleportationAllowed = false;
  76612. if (hit.pickedMesh !== this._currentMeshSelected) {
  76613. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76614. this.onNewMeshPicked.notifyObservers(hit);
  76615. this._currentMeshSelected = hit.pickedMesh;
  76616. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76617. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76618. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76619. this._isActionableMesh = true;
  76620. }
  76621. else {
  76622. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76623. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76624. this._isActionableMesh = false;
  76625. }
  76626. try {
  76627. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76628. }
  76629. catch (err) {
  76630. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76631. }
  76632. }
  76633. else {
  76634. if (this._currentMeshSelected) {
  76635. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76636. }
  76637. this._currentMeshSelected = null;
  76638. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76639. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76640. }
  76641. }
  76642. }
  76643. else {
  76644. this._currentHit = null;
  76645. this._currentMeshSelected = null;
  76646. this._teleportationAllowed = false;
  76647. this._hideTeleportationTarget();
  76648. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76649. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76650. }
  76651. };
  76652. /**
  76653. * Sets the color of the laser ray from the vr controllers.
  76654. * @param color new color for the ray.
  76655. */
  76656. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76657. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76658. this._leftLaserPointer.material.emissiveColor = color;
  76659. }
  76660. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76661. this._rightLaserPointer.material.emissiveColor = color;
  76662. }
  76663. };
  76664. /**
  76665. * Sets the color of the ray from the vr headsets gaze.
  76666. * @param color new color for the ray.
  76667. */
  76668. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  76669. if (this._gazeTracker.material) {
  76670. this._gazeTracker.material.emissiveColor = color;
  76671. }
  76672. };
  76673. /**
  76674. * Exits VR and disposes of the vr experience helper
  76675. */
  76676. VRExperienceHelper.prototype.dispose = function () {
  76677. if (this.isInVRMode) {
  76678. this.exitVR();
  76679. }
  76680. if (this._passProcessMove) {
  76681. this._passProcessMove.dispose();
  76682. }
  76683. if (this._postProcessMove) {
  76684. this._postProcessMove.dispose();
  76685. }
  76686. if (this._webVRCamera) {
  76687. this._webVRCamera.dispose();
  76688. }
  76689. if (this._vrDeviceOrientationCamera) {
  76690. this._vrDeviceOrientationCamera.dispose();
  76691. }
  76692. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  76693. document.body.removeChild(this._btnVR);
  76694. }
  76695. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  76696. this._deviceOrientationCamera.dispose();
  76697. }
  76698. if (this._gazeTracker) {
  76699. this._gazeTracker.dispose();
  76700. }
  76701. if (this._teleportationTarget) {
  76702. this._teleportationTarget.dispose();
  76703. }
  76704. this._floorMeshesCollection = [];
  76705. document.removeEventListener("keydown", this._onKeyDown);
  76706. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76707. window.removeEventListener("resize", this._onResize);
  76708. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  76709. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  76710. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  76711. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  76712. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  76713. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  76714. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  76715. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76716. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  76717. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  76718. this._scene.unregisterBeforeRender(this.beforeRender);
  76719. };
  76720. /**
  76721. * Gets the name of the VRExperienceHelper class
  76722. * @returns "VRExperienceHelper"
  76723. */
  76724. VRExperienceHelper.prototype.getClassName = function () {
  76725. return "VRExperienceHelper";
  76726. };
  76727. return VRExperienceHelper;
  76728. }());
  76729. BABYLON.VRExperienceHelper = VRExperienceHelper;
  76730. })(BABYLON || (BABYLON = {}));
  76731. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  76732. // Mainly based on these 2 articles :
  76733. // 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
  76734. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  76735. var BABYLON;
  76736. (function (BABYLON) {
  76737. var JoystickAxis;
  76738. (function (JoystickAxis) {
  76739. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  76740. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  76741. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  76742. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  76743. var VirtualJoystick = /** @class */ (function () {
  76744. function VirtualJoystick(leftJoystick) {
  76745. var _this = this;
  76746. if (leftJoystick) {
  76747. this._leftJoystick = true;
  76748. }
  76749. else {
  76750. this._leftJoystick = false;
  76751. }
  76752. VirtualJoystick._globalJoystickIndex++;
  76753. // By default left & right arrow keys are moving the X
  76754. // and up & down keys are moving the Y
  76755. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76756. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76757. this.reverseLeftRight = false;
  76758. this.reverseUpDown = false;
  76759. // collections of pointers
  76760. this._touches = new BABYLON.StringDictionary();
  76761. this.deltaPosition = BABYLON.Vector3.Zero();
  76762. this._joystickSensibility = 25;
  76763. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76764. this._onResize = function (evt) {
  76765. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76766. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76767. if (VirtualJoystick.vjCanvas) {
  76768. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  76769. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  76770. }
  76771. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  76772. };
  76773. // injecting a canvas element on top of the canvas 3D game
  76774. if (!VirtualJoystick.vjCanvas) {
  76775. window.addEventListener("resize", this._onResize, false);
  76776. VirtualJoystick.vjCanvas = document.createElement("canvas");
  76777. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76778. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76779. VirtualJoystick.vjCanvas.width = window.innerWidth;
  76780. VirtualJoystick.vjCanvas.height = window.innerHeight;
  76781. VirtualJoystick.vjCanvas.style.width = "100%";
  76782. VirtualJoystick.vjCanvas.style.height = "100%";
  76783. VirtualJoystick.vjCanvas.style.position = "absolute";
  76784. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  76785. VirtualJoystick.vjCanvas.style.top = "0px";
  76786. VirtualJoystick.vjCanvas.style.left = "0px";
  76787. VirtualJoystick.vjCanvas.style.zIndex = "5";
  76788. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  76789. // Support for jQuery PEP polyfill
  76790. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  76791. var context = VirtualJoystick.vjCanvas.getContext('2d');
  76792. if (!context) {
  76793. throw new Error("Unable to create canvas for virtual joystick");
  76794. }
  76795. VirtualJoystick.vjCanvasContext = context;
  76796. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  76797. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76798. document.body.appendChild(VirtualJoystick.vjCanvas);
  76799. }
  76800. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  76801. this.pressed = false;
  76802. // default joystick color
  76803. this._joystickColor = "cyan";
  76804. this._joystickPointerID = -1;
  76805. // current joystick position
  76806. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  76807. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  76808. // origin joystick position
  76809. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  76810. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  76811. this._onPointerDownHandlerRef = function (evt) {
  76812. _this._onPointerDown(evt);
  76813. };
  76814. this._onPointerMoveHandlerRef = function (evt) {
  76815. _this._onPointerMove(evt);
  76816. };
  76817. this._onPointerUpHandlerRef = function (evt) {
  76818. _this._onPointerUp(evt);
  76819. };
  76820. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  76821. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  76822. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  76823. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  76824. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  76825. evt.preventDefault(); // Disables system menu
  76826. }, false);
  76827. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76828. }
  76829. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  76830. this._joystickSensibility = newJoystickSensibility;
  76831. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76832. };
  76833. VirtualJoystick.prototype._onPointerDown = function (e) {
  76834. var positionOnScreenCondition;
  76835. e.preventDefault();
  76836. if (this._leftJoystick === true) {
  76837. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  76838. }
  76839. else {
  76840. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  76841. }
  76842. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  76843. // First contact will be dedicated to the virtual joystick
  76844. this._joystickPointerID = e.pointerId;
  76845. this._joystickPointerStartPos.x = e.clientX;
  76846. this._joystickPointerStartPos.y = e.clientY;
  76847. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  76848. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  76849. this._deltaJoystickVector.x = 0;
  76850. this._deltaJoystickVector.y = 0;
  76851. this.pressed = true;
  76852. this._touches.add(e.pointerId.toString(), e);
  76853. }
  76854. else {
  76855. // You can only trigger the action buttons with a joystick declared
  76856. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  76857. this._action();
  76858. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  76859. }
  76860. }
  76861. };
  76862. VirtualJoystick.prototype._onPointerMove = function (e) {
  76863. // If the current pointer is the one associated to the joystick (first touch contact)
  76864. if (this._joystickPointerID == e.pointerId) {
  76865. this._joystickPointerPos.x = e.clientX;
  76866. this._joystickPointerPos.y = e.clientY;
  76867. this._deltaJoystickVector = this._joystickPointerPos.clone();
  76868. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  76869. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  76870. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  76871. switch (this._axisTargetedByLeftAndRight) {
  76872. case JoystickAxis.X:
  76873. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  76874. break;
  76875. case JoystickAxis.Y:
  76876. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  76877. break;
  76878. case JoystickAxis.Z:
  76879. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  76880. break;
  76881. }
  76882. var directionUpDown = this.reverseUpDown ? 1 : -1;
  76883. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  76884. switch (this._axisTargetedByUpAndDown) {
  76885. case JoystickAxis.X:
  76886. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  76887. break;
  76888. case JoystickAxis.Y:
  76889. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  76890. break;
  76891. case JoystickAxis.Z:
  76892. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  76893. break;
  76894. }
  76895. }
  76896. else {
  76897. var data = this._touches.get(e.pointerId.toString());
  76898. if (data) {
  76899. data.x = e.clientX;
  76900. data.y = e.clientY;
  76901. }
  76902. }
  76903. };
  76904. VirtualJoystick.prototype._onPointerUp = function (e) {
  76905. if (this._joystickPointerID == e.pointerId) {
  76906. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  76907. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  76908. this._joystickPointerID = -1;
  76909. this.pressed = false;
  76910. }
  76911. else {
  76912. var touch = this._touches.get(e.pointerId.toString());
  76913. if (touch) {
  76914. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76915. }
  76916. }
  76917. this._deltaJoystickVector.x = 0;
  76918. this._deltaJoystickVector.y = 0;
  76919. this._touches.remove(e.pointerId.toString());
  76920. };
  76921. /**
  76922. * Change the color of the virtual joystick
  76923. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  76924. */
  76925. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  76926. this._joystickColor = newColor;
  76927. };
  76928. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  76929. this._action = action;
  76930. };
  76931. // Define which axis you'd like to control for left & right
  76932. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  76933. switch (axis) {
  76934. case JoystickAxis.X:
  76935. case JoystickAxis.Y:
  76936. case JoystickAxis.Z:
  76937. this._axisTargetedByLeftAndRight = axis;
  76938. break;
  76939. default:
  76940. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76941. break;
  76942. }
  76943. };
  76944. // Define which axis you'd like to control for up & down
  76945. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  76946. switch (axis) {
  76947. case JoystickAxis.X:
  76948. case JoystickAxis.Y:
  76949. case JoystickAxis.Z:
  76950. this._axisTargetedByUpAndDown = axis;
  76951. break;
  76952. default:
  76953. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76954. break;
  76955. }
  76956. };
  76957. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  76958. var _this = this;
  76959. if (this.pressed) {
  76960. this._touches.forEach(function (key, touch) {
  76961. if (touch.pointerId === _this._joystickPointerID) {
  76962. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  76963. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  76964. VirtualJoystick.vjCanvasContext.beginPath();
  76965. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76966. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76967. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  76968. VirtualJoystick.vjCanvasContext.stroke();
  76969. VirtualJoystick.vjCanvasContext.closePath();
  76970. VirtualJoystick.vjCanvasContext.beginPath();
  76971. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76972. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76973. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  76974. VirtualJoystick.vjCanvasContext.stroke();
  76975. VirtualJoystick.vjCanvasContext.closePath();
  76976. VirtualJoystick.vjCanvasContext.beginPath();
  76977. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  76978. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  76979. VirtualJoystick.vjCanvasContext.stroke();
  76980. VirtualJoystick.vjCanvasContext.closePath();
  76981. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  76982. }
  76983. else {
  76984. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  76985. VirtualJoystick.vjCanvasContext.beginPath();
  76986. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  76987. VirtualJoystick.vjCanvasContext.beginPath();
  76988. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  76989. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  76990. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  76991. VirtualJoystick.vjCanvasContext.stroke();
  76992. VirtualJoystick.vjCanvasContext.closePath();
  76993. touch.prevX = touch.x;
  76994. touch.prevY = touch.y;
  76995. }
  76996. ;
  76997. });
  76998. }
  76999. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77000. };
  77001. VirtualJoystick.prototype.releaseCanvas = function () {
  77002. if (VirtualJoystick.vjCanvas) {
  77003. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  77004. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  77005. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  77006. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  77007. window.removeEventListener("resize", this._onResize);
  77008. document.body.removeChild(VirtualJoystick.vjCanvas);
  77009. VirtualJoystick.vjCanvas = null;
  77010. }
  77011. };
  77012. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  77013. VirtualJoystick._globalJoystickIndex = 0;
  77014. return VirtualJoystick;
  77015. }());
  77016. BABYLON.VirtualJoystick = VirtualJoystick;
  77017. })(BABYLON || (BABYLON = {}));
  77018. //# sourceMappingURL=babylon.virtualJoystick.js.map
  77019. var BABYLON;
  77020. (function (BABYLON) {
  77021. // We're mainly based on the logic defined into the FreeCamera code
  77022. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  77023. __extends(VirtualJoysticksCamera, _super);
  77024. function VirtualJoysticksCamera(name, position, scene) {
  77025. var _this = _super.call(this, name, position, scene) || this;
  77026. _this.inputs.addVirtualJoystick();
  77027. return _this;
  77028. }
  77029. VirtualJoysticksCamera.prototype.getClassName = function () {
  77030. return "VirtualJoysticksCamera";
  77031. };
  77032. return VirtualJoysticksCamera;
  77033. }(BABYLON.FreeCamera));
  77034. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  77035. })(BABYLON || (BABYLON = {}));
  77036. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  77037. var BABYLON;
  77038. (function (BABYLON) {
  77039. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  77040. function FreeCameraVirtualJoystickInput() {
  77041. }
  77042. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  77043. return this._leftjoystick;
  77044. };
  77045. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  77046. return this._rightjoystick;
  77047. };
  77048. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  77049. if (this._leftjoystick) {
  77050. var camera = this.camera;
  77051. var speed = camera._computeLocalCameraSpeed() * 50;
  77052. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  77053. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  77054. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  77055. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  77056. if (!this._leftjoystick.pressed) {
  77057. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  77058. }
  77059. if (!this._rightjoystick.pressed) {
  77060. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  77061. }
  77062. }
  77063. };
  77064. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  77065. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  77066. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  77067. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  77068. this._leftjoystick.setJoystickSensibility(0.15);
  77069. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  77070. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  77071. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  77072. this._rightjoystick.reverseUpDown = true;
  77073. this._rightjoystick.setJoystickSensibility(0.05);
  77074. this._rightjoystick.setJoystickColor("yellow");
  77075. };
  77076. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  77077. this._leftjoystick.releaseCanvas();
  77078. this._rightjoystick.releaseCanvas();
  77079. };
  77080. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  77081. return "FreeCameraVirtualJoystickInput";
  77082. };
  77083. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  77084. return "virtualJoystick";
  77085. };
  77086. return FreeCameraVirtualJoystickInput;
  77087. }());
  77088. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  77089. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  77090. })(BABYLON || (BABYLON = {}));
  77091. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  77092. var BABYLON;
  77093. (function (BABYLON) {
  77094. var SimplificationSettings = /** @class */ (function () {
  77095. function SimplificationSettings(quality, distance, optimizeMesh) {
  77096. this.quality = quality;
  77097. this.distance = distance;
  77098. this.optimizeMesh = optimizeMesh;
  77099. }
  77100. return SimplificationSettings;
  77101. }());
  77102. BABYLON.SimplificationSettings = SimplificationSettings;
  77103. var SimplificationQueue = /** @class */ (function () {
  77104. function SimplificationQueue() {
  77105. this.running = false;
  77106. this._simplificationArray = [];
  77107. }
  77108. SimplificationQueue.prototype.addTask = function (task) {
  77109. this._simplificationArray.push(task);
  77110. };
  77111. SimplificationQueue.prototype.executeNext = function () {
  77112. var task = this._simplificationArray.pop();
  77113. if (task) {
  77114. this.running = true;
  77115. this.runSimplification(task);
  77116. }
  77117. else {
  77118. this.running = false;
  77119. }
  77120. };
  77121. SimplificationQueue.prototype.runSimplification = function (task) {
  77122. var _this = this;
  77123. if (task.parallelProcessing) {
  77124. //parallel simplifier
  77125. task.settings.forEach(function (setting) {
  77126. var simplifier = _this.getSimplifier(task);
  77127. simplifier.simplify(setting, function (newMesh) {
  77128. task.mesh.addLODLevel(setting.distance, newMesh);
  77129. newMesh.isVisible = true;
  77130. //check if it is the last
  77131. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  77132. //all done, run the success callback.
  77133. task.successCallback();
  77134. }
  77135. _this.executeNext();
  77136. });
  77137. });
  77138. }
  77139. else {
  77140. //single simplifier.
  77141. var simplifier = this.getSimplifier(task);
  77142. var runDecimation = function (setting, callback) {
  77143. simplifier.simplify(setting, function (newMesh) {
  77144. task.mesh.addLODLevel(setting.distance, newMesh);
  77145. newMesh.isVisible = true;
  77146. //run the next quality level
  77147. callback();
  77148. });
  77149. };
  77150. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  77151. runDecimation(task.settings[loop.index], function () {
  77152. loop.executeNext();
  77153. });
  77154. }, function () {
  77155. //execution ended, run the success callback.
  77156. if (task.successCallback) {
  77157. task.successCallback();
  77158. }
  77159. _this.executeNext();
  77160. });
  77161. }
  77162. };
  77163. SimplificationQueue.prototype.getSimplifier = function (task) {
  77164. switch (task.simplificationType) {
  77165. case SimplificationType.QUADRATIC:
  77166. default:
  77167. return new QuadraticErrorSimplification(task.mesh);
  77168. }
  77169. };
  77170. return SimplificationQueue;
  77171. }());
  77172. BABYLON.SimplificationQueue = SimplificationQueue;
  77173. /**
  77174. * The implemented types of simplification.
  77175. * At the moment only Quadratic Error Decimation is implemented.
  77176. */
  77177. var SimplificationType;
  77178. (function (SimplificationType) {
  77179. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  77180. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  77181. var DecimationTriangle = /** @class */ (function () {
  77182. function DecimationTriangle(vertices) {
  77183. this.vertices = vertices;
  77184. this.error = new Array(4);
  77185. this.deleted = false;
  77186. this.isDirty = false;
  77187. this.deletePending = false;
  77188. this.borderFactor = 0;
  77189. }
  77190. return DecimationTriangle;
  77191. }());
  77192. BABYLON.DecimationTriangle = DecimationTriangle;
  77193. var DecimationVertex = /** @class */ (function () {
  77194. function DecimationVertex(position, id) {
  77195. this.position = position;
  77196. this.id = id;
  77197. this.isBorder = true;
  77198. this.q = new QuadraticMatrix();
  77199. this.triangleCount = 0;
  77200. this.triangleStart = 0;
  77201. this.originalOffsets = [];
  77202. }
  77203. DecimationVertex.prototype.updatePosition = function (newPosition) {
  77204. this.position.copyFrom(newPosition);
  77205. };
  77206. return DecimationVertex;
  77207. }());
  77208. BABYLON.DecimationVertex = DecimationVertex;
  77209. var QuadraticMatrix = /** @class */ (function () {
  77210. function QuadraticMatrix(data) {
  77211. this.data = new Array(10);
  77212. for (var i = 0; i < 10; ++i) {
  77213. if (data && data[i]) {
  77214. this.data[i] = data[i];
  77215. }
  77216. else {
  77217. this.data[i] = 0;
  77218. }
  77219. }
  77220. }
  77221. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  77222. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  77223. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  77224. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  77225. return det;
  77226. };
  77227. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  77228. for (var i = 0; i < 10; ++i) {
  77229. this.data[i] += matrix.data[i];
  77230. }
  77231. };
  77232. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  77233. for (var i = 0; i < 10; ++i) {
  77234. this.data[i] += data[i];
  77235. }
  77236. };
  77237. QuadraticMatrix.prototype.add = function (matrix) {
  77238. var m = new QuadraticMatrix();
  77239. for (var i = 0; i < 10; ++i) {
  77240. m.data[i] = this.data[i] + matrix.data[i];
  77241. }
  77242. return m;
  77243. };
  77244. QuadraticMatrix.FromData = function (a, b, c, d) {
  77245. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  77246. };
  77247. //returning an array to avoid garbage collection
  77248. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  77249. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  77250. };
  77251. return QuadraticMatrix;
  77252. }());
  77253. BABYLON.QuadraticMatrix = QuadraticMatrix;
  77254. var Reference = /** @class */ (function () {
  77255. function Reference(vertexId, triangleId) {
  77256. this.vertexId = vertexId;
  77257. this.triangleId = triangleId;
  77258. }
  77259. return Reference;
  77260. }());
  77261. BABYLON.Reference = Reference;
  77262. /**
  77263. * An implementation of the Quadratic Error simplification algorithm.
  77264. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  77265. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  77266. * @author RaananW
  77267. */
  77268. var QuadraticErrorSimplification = /** @class */ (function () {
  77269. function QuadraticErrorSimplification(_mesh) {
  77270. this._mesh = _mesh;
  77271. this.syncIterations = 5000;
  77272. this.aggressiveness = 7;
  77273. this.decimationIterations = 100;
  77274. this.boundingBoxEpsilon = BABYLON.Epsilon;
  77275. }
  77276. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  77277. var _this = this;
  77278. this.initDecimatedMesh();
  77279. //iterating through the submeshes array, one after the other.
  77280. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  77281. _this.initWithMesh(loop.index, function () {
  77282. _this.runDecimation(settings, loop.index, function () {
  77283. loop.executeNext();
  77284. });
  77285. }, settings.optimizeMesh);
  77286. }, function () {
  77287. setTimeout(function () {
  77288. successCallback(_this._reconstructedMesh);
  77289. }, 0);
  77290. });
  77291. };
  77292. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  77293. var _this = this;
  77294. var targetCount = ~~(this.triangles.length * settings.quality);
  77295. var deletedTriangles = 0;
  77296. var triangleCount = this.triangles.length;
  77297. var iterationFunction = function (iteration, callback) {
  77298. setTimeout(function () {
  77299. if (iteration % 5 === 0) {
  77300. _this.updateMesh(iteration === 0);
  77301. }
  77302. for (var i = 0; i < _this.triangles.length; ++i) {
  77303. _this.triangles[i].isDirty = false;
  77304. }
  77305. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  77306. var trianglesIterator = function (i) {
  77307. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  77308. var t = _this.triangles[tIdx];
  77309. if (!t)
  77310. return;
  77311. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  77312. return;
  77313. }
  77314. for (var j = 0; j < 3; ++j) {
  77315. if (t.error[j] < threshold) {
  77316. var deleted0 = [];
  77317. var deleted1 = [];
  77318. var v0 = t.vertices[j];
  77319. var v1 = t.vertices[(j + 1) % 3];
  77320. if (v0.isBorder || v1.isBorder)
  77321. continue;
  77322. var p = BABYLON.Vector3.Zero();
  77323. var n = BABYLON.Vector3.Zero();
  77324. var uv = BABYLON.Vector2.Zero();
  77325. var color = new BABYLON.Color4(0, 0, 0, 1);
  77326. _this.calculateError(v0, v1, p, n, uv, color);
  77327. var delTr = new Array();
  77328. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  77329. continue;
  77330. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  77331. continue;
  77332. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  77333. continue;
  77334. var uniqueArray = new Array();
  77335. delTr.forEach(function (deletedT) {
  77336. if (uniqueArray.indexOf(deletedT) === -1) {
  77337. deletedT.deletePending = true;
  77338. uniqueArray.push(deletedT);
  77339. }
  77340. });
  77341. if (uniqueArray.length % 2 !== 0) {
  77342. continue;
  77343. }
  77344. v0.q = v1.q.add(v0.q);
  77345. v0.updatePosition(p);
  77346. var tStart = _this.references.length;
  77347. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  77348. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  77349. var tCount = _this.references.length - tStart;
  77350. if (tCount <= v0.triangleCount) {
  77351. if (tCount) {
  77352. for (var c = 0; c < tCount; c++) {
  77353. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  77354. }
  77355. }
  77356. }
  77357. else {
  77358. v0.triangleStart = tStart;
  77359. }
  77360. v0.triangleCount = tCount;
  77361. break;
  77362. }
  77363. }
  77364. };
  77365. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  77366. }, 0);
  77367. };
  77368. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  77369. if (triangleCount - deletedTriangles <= targetCount)
  77370. loop.breakLoop();
  77371. else {
  77372. iterationFunction(loop.index, function () {
  77373. loop.executeNext();
  77374. });
  77375. }
  77376. }, function () {
  77377. setTimeout(function () {
  77378. //reconstruct this part of the mesh
  77379. _this.reconstructMesh(submeshIndex);
  77380. successCallback();
  77381. }, 0);
  77382. });
  77383. };
  77384. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  77385. var _this = this;
  77386. this.vertices = [];
  77387. this.triangles = [];
  77388. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  77389. var indices = this._mesh.getIndices();
  77390. var submesh = this._mesh.subMeshes[submeshIndex];
  77391. var findInVertices = function (positionToSearch) {
  77392. if (optimizeMesh) {
  77393. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  77394. if (_this.vertices[ii].position.equals(positionToSearch)) {
  77395. return _this.vertices[ii];
  77396. }
  77397. }
  77398. }
  77399. return null;
  77400. };
  77401. var vertexReferences = [];
  77402. var vertexInit = function (i) {
  77403. if (!positionData) {
  77404. return;
  77405. }
  77406. var offset = i + submesh.verticesStart;
  77407. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  77408. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  77409. vertex.originalOffsets.push(offset);
  77410. if (vertex.id === _this.vertices.length) {
  77411. _this.vertices.push(vertex);
  77412. }
  77413. vertexReferences.push(vertex.id);
  77414. };
  77415. //var totalVertices = mesh.getTotalVertices();
  77416. var totalVertices = submesh.verticesCount;
  77417. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  77418. var indicesInit = function (i) {
  77419. if (!indices) {
  77420. return;
  77421. }
  77422. var offset = (submesh.indexStart / 3) + i;
  77423. var pos = (offset * 3);
  77424. var i0 = indices[pos + 0];
  77425. var i1 = indices[pos + 1];
  77426. var i2 = indices[pos + 2];
  77427. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  77428. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  77429. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  77430. var triangle = new DecimationTriangle([v0, v1, v2]);
  77431. triangle.originalOffset = pos;
  77432. _this.triangles.push(triangle);
  77433. };
  77434. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  77435. _this.init(callback);
  77436. });
  77437. });
  77438. };
  77439. QuadraticErrorSimplification.prototype.init = function (callback) {
  77440. var _this = this;
  77441. var triangleInit1 = function (i) {
  77442. var t = _this.triangles[i];
  77443. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  77444. for (var j = 0; j < 3; j++) {
  77445. 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))));
  77446. }
  77447. };
  77448. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  77449. var triangleInit2 = function (i) {
  77450. var t = _this.triangles[i];
  77451. for (var j = 0; j < 3; ++j) {
  77452. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  77453. }
  77454. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77455. };
  77456. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  77457. callback();
  77458. });
  77459. });
  77460. };
  77461. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  77462. var newTriangles = [];
  77463. var i;
  77464. for (i = 0; i < this.vertices.length; ++i) {
  77465. this.vertices[i].triangleCount = 0;
  77466. }
  77467. var t;
  77468. var j;
  77469. for (i = 0; i < this.triangles.length; ++i) {
  77470. if (!this.triangles[i].deleted) {
  77471. t = this.triangles[i];
  77472. for (j = 0; j < 3; ++j) {
  77473. t.vertices[j].triangleCount = 1;
  77474. }
  77475. newTriangles.push(t);
  77476. }
  77477. }
  77478. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  77479. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  77480. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  77481. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  77482. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  77483. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  77484. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  77485. var vertexCount = 0;
  77486. for (i = 0; i < this.vertices.length; ++i) {
  77487. var vertex = this.vertices[i];
  77488. vertex.id = vertexCount;
  77489. if (vertex.triangleCount) {
  77490. vertex.originalOffsets.forEach(function (originalOffset) {
  77491. if (!normalData) {
  77492. return;
  77493. }
  77494. newPositionData.push(vertex.position.x);
  77495. newPositionData.push(vertex.position.y);
  77496. newPositionData.push(vertex.position.z);
  77497. newNormalData.push(normalData[originalOffset * 3]);
  77498. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  77499. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  77500. if (uvs && uvs.length) {
  77501. newUVsData.push(uvs[(originalOffset * 2)]);
  77502. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  77503. }
  77504. else if (colorsData && colorsData.length) {
  77505. newColorsData.push(colorsData[(originalOffset * 4)]);
  77506. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  77507. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  77508. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  77509. }
  77510. ++vertexCount;
  77511. });
  77512. }
  77513. }
  77514. var startingIndex = this._reconstructedMesh.getTotalIndices();
  77515. var startingVertex = this._reconstructedMesh.getTotalVertices();
  77516. var submeshesArray = this._reconstructedMesh.subMeshes;
  77517. this._reconstructedMesh.subMeshes = [];
  77518. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  77519. var originalIndices = this._mesh.getIndices();
  77520. for (i = 0; i < newTriangles.length; ++i) {
  77521. t = newTriangles[i]; //now get the new referencing point for each vertex
  77522. [0, 1, 2].forEach(function (idx) {
  77523. var id = originalIndices[t.originalOffset + idx];
  77524. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  77525. if (offset < 0)
  77526. offset = 0;
  77527. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  77528. });
  77529. }
  77530. //overwriting the old vertex buffers and indices.
  77531. this._reconstructedMesh.setIndices(newIndicesArray);
  77532. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  77533. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  77534. if (newUVsData.length > 0)
  77535. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  77536. if (newColorsData.length > 0)
  77537. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  77538. //create submesh
  77539. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  77540. if (submeshIndex > 0) {
  77541. this._reconstructedMesh.subMeshes = [];
  77542. submeshesArray.forEach(function (submesh) {
  77543. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  77544. });
  77545. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  77546. }
  77547. };
  77548. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  77549. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  77550. this._reconstructedMesh.material = this._mesh.material;
  77551. this._reconstructedMesh.parent = this._mesh.parent;
  77552. this._reconstructedMesh.isVisible = false;
  77553. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  77554. };
  77555. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  77556. for (var i = 0; i < vertex1.triangleCount; ++i) {
  77557. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  77558. if (t.deleted)
  77559. continue;
  77560. var s = this.references[vertex1.triangleStart + i].vertexId;
  77561. var v1 = t.vertices[(s + 1) % 3];
  77562. var v2 = t.vertices[(s + 2) % 3];
  77563. if ((v1 === vertex2 || v2 === vertex2)) {
  77564. deletedArray[i] = true;
  77565. delTr.push(t);
  77566. continue;
  77567. }
  77568. var d1 = v1.position.subtract(point);
  77569. d1 = d1.normalize();
  77570. var d2 = v2.position.subtract(point);
  77571. d2 = d2.normalize();
  77572. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  77573. return true;
  77574. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  77575. deletedArray[i] = false;
  77576. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  77577. return true;
  77578. }
  77579. return false;
  77580. };
  77581. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  77582. var newDeleted = deletedTriangles;
  77583. for (var i = 0; i < vertex.triangleCount; ++i) {
  77584. var ref = this.references[vertex.triangleStart + i];
  77585. var t = this.triangles[ref.triangleId];
  77586. if (t.deleted)
  77587. continue;
  77588. if (deletedArray[i] && t.deletePending) {
  77589. t.deleted = true;
  77590. newDeleted++;
  77591. continue;
  77592. }
  77593. t.vertices[ref.vertexId] = origVertex;
  77594. t.isDirty = true;
  77595. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  77596. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  77597. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  77598. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77599. this.references.push(ref);
  77600. }
  77601. return newDeleted;
  77602. };
  77603. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  77604. for (var i = 0; i < this.vertices.length; ++i) {
  77605. var vCount = [];
  77606. var vId = [];
  77607. var v = this.vertices[i];
  77608. var j;
  77609. for (j = 0; j < v.triangleCount; ++j) {
  77610. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77611. for (var ii = 0; ii < 3; ii++) {
  77612. var ofs = 0;
  77613. var vv = triangle.vertices[ii];
  77614. while (ofs < vCount.length) {
  77615. if (vId[ofs] === vv.id)
  77616. break;
  77617. ++ofs;
  77618. }
  77619. if (ofs === vCount.length) {
  77620. vCount.push(1);
  77621. vId.push(vv.id);
  77622. }
  77623. else {
  77624. vCount[ofs]++;
  77625. }
  77626. }
  77627. }
  77628. for (j = 0; j < vCount.length; ++j) {
  77629. if (vCount[j] === 1) {
  77630. this.vertices[vId[j]].isBorder = true;
  77631. }
  77632. else {
  77633. this.vertices[vId[j]].isBorder = false;
  77634. }
  77635. }
  77636. }
  77637. };
  77638. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77639. if (identifyBorders === void 0) { identifyBorders = false; }
  77640. var i;
  77641. if (!identifyBorders) {
  77642. var newTrianglesVector = [];
  77643. for (i = 0; i < this.triangles.length; ++i) {
  77644. if (!this.triangles[i].deleted) {
  77645. newTrianglesVector.push(this.triangles[i]);
  77646. }
  77647. }
  77648. this.triangles = newTrianglesVector;
  77649. }
  77650. for (i = 0; i < this.vertices.length; ++i) {
  77651. this.vertices[i].triangleCount = 0;
  77652. this.vertices[i].triangleStart = 0;
  77653. }
  77654. var t;
  77655. var j;
  77656. var v;
  77657. for (i = 0; i < this.triangles.length; ++i) {
  77658. t = this.triangles[i];
  77659. for (j = 0; j < 3; ++j) {
  77660. v = t.vertices[j];
  77661. v.triangleCount++;
  77662. }
  77663. }
  77664. var tStart = 0;
  77665. for (i = 0; i < this.vertices.length; ++i) {
  77666. this.vertices[i].triangleStart = tStart;
  77667. tStart += this.vertices[i].triangleCount;
  77668. this.vertices[i].triangleCount = 0;
  77669. }
  77670. var newReferences = new Array(this.triangles.length * 3);
  77671. for (i = 0; i < this.triangles.length; ++i) {
  77672. t = this.triangles[i];
  77673. for (j = 0; j < 3; ++j) {
  77674. v = t.vertices[j];
  77675. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  77676. v.triangleCount++;
  77677. }
  77678. }
  77679. this.references = newReferences;
  77680. if (identifyBorders) {
  77681. this.identifyBorder();
  77682. }
  77683. };
  77684. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  77685. var x = point.x;
  77686. var y = point.y;
  77687. var z = point.z;
  77688. 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
  77689. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  77690. };
  77691. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  77692. var q = vertex1.q.add(vertex2.q);
  77693. var border = vertex1.isBorder && vertex2.isBorder;
  77694. var error = 0;
  77695. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  77696. if (qDet !== 0 && !border) {
  77697. if (!pointResult) {
  77698. pointResult = BABYLON.Vector3.Zero();
  77699. }
  77700. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  77701. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  77702. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  77703. error = this.vertexError(q, pointResult);
  77704. }
  77705. else {
  77706. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  77707. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  77708. var error1 = this.vertexError(q, vertex1.position);
  77709. var error2 = this.vertexError(q, vertex2.position);
  77710. var error3 = this.vertexError(q, p3);
  77711. error = Math.min(error1, error2, error3);
  77712. if (error === error1) {
  77713. if (pointResult) {
  77714. pointResult.copyFrom(vertex1.position);
  77715. }
  77716. }
  77717. else if (error === error2) {
  77718. if (pointResult) {
  77719. pointResult.copyFrom(vertex2.position);
  77720. }
  77721. }
  77722. else {
  77723. if (pointResult) {
  77724. pointResult.copyFrom(p3);
  77725. }
  77726. }
  77727. }
  77728. return error;
  77729. };
  77730. return QuadraticErrorSimplification;
  77731. }());
  77732. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  77733. })(BABYLON || (BABYLON = {}));
  77734. //# sourceMappingURL=babylon.meshSimplification.js.map
  77735. var BABYLON;
  77736. (function (BABYLON) {
  77737. var MeshLODLevel = /** @class */ (function () {
  77738. function MeshLODLevel(distance, mesh) {
  77739. this.distance = distance;
  77740. this.mesh = mesh;
  77741. }
  77742. return MeshLODLevel;
  77743. }());
  77744. BABYLON.MeshLODLevel = MeshLODLevel;
  77745. })(BABYLON || (BABYLON = {}));
  77746. //# sourceMappingURL=babylon.meshLODLevel.js.map
  77747. var BABYLON;
  77748. (function (BABYLON) {
  77749. /**
  77750. * Defines the root class used to create scene optimization to use with SceneOptimizer
  77751. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77752. */
  77753. var SceneOptimization = /** @class */ (function () {
  77754. /**
  77755. * Creates the SceneOptimization object
  77756. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77757. * @param desc defines the description associated with the optimization
  77758. */
  77759. function SceneOptimization(
  77760. /**
  77761. * Defines the priority of this optimization (0 by default which means first in the list)
  77762. */
  77763. priority) {
  77764. if (priority === void 0) { priority = 0; }
  77765. this.priority = priority;
  77766. }
  77767. /**
  77768. * Gets a string describing the action executed by the current optimization
  77769. * @returns description string
  77770. */
  77771. SceneOptimization.prototype.getDescription = function () {
  77772. return "";
  77773. };
  77774. /**
  77775. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77776. * @param scene defines the current scene where to apply this optimization
  77777. * @param optimizer defines the current optimizer
  77778. * @returns true if everything that can be done was applied
  77779. */
  77780. SceneOptimization.prototype.apply = function (scene, optimizer) {
  77781. return true;
  77782. };
  77783. ;
  77784. return SceneOptimization;
  77785. }());
  77786. BABYLON.SceneOptimization = SceneOptimization;
  77787. /**
  77788. * Defines an optimization used to reduce the size of render target textures
  77789. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77790. */
  77791. var TextureOptimization = /** @class */ (function (_super) {
  77792. __extends(TextureOptimization, _super);
  77793. /**
  77794. * Creates the TextureOptimization object
  77795. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77796. * @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
  77797. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77798. */
  77799. function TextureOptimization(
  77800. /**
  77801. * Defines the priority of this optimization (0 by default which means first in the list)
  77802. */
  77803. priority,
  77804. /**
  77805. * 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
  77806. */
  77807. maximumSize,
  77808. /**
  77809. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77810. */
  77811. step) {
  77812. if (priority === void 0) { priority = 0; }
  77813. if (maximumSize === void 0) { maximumSize = 1024; }
  77814. if (step === void 0) { step = 0.5; }
  77815. var _this = _super.call(this, priority) || this;
  77816. _this.priority = priority;
  77817. _this.maximumSize = maximumSize;
  77818. _this.step = step;
  77819. return _this;
  77820. }
  77821. /**
  77822. * Gets a string describing the action executed by the current optimization
  77823. * @returns description string
  77824. */
  77825. TextureOptimization.prototype.getDescription = function () {
  77826. return "Reducing render target texture size to " + this.maximumSize;
  77827. };
  77828. /**
  77829. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77830. * @param scene defines the current scene where to apply this optimization
  77831. * @param optimizer defines the current optimizer
  77832. * @returns true if everything that can be done was applied
  77833. */
  77834. TextureOptimization.prototype.apply = function (scene, optimizer) {
  77835. var allDone = true;
  77836. for (var index = 0; index < scene.textures.length; index++) {
  77837. var texture = scene.textures[index];
  77838. if (!texture.canRescale || texture.getContext) {
  77839. continue;
  77840. }
  77841. var currentSize = texture.getSize();
  77842. var maxDimension = Math.max(currentSize.width, currentSize.height);
  77843. if (maxDimension > this.maximumSize) {
  77844. texture.scale(this.step);
  77845. allDone = false;
  77846. }
  77847. }
  77848. return allDone;
  77849. };
  77850. return TextureOptimization;
  77851. }(SceneOptimization));
  77852. BABYLON.TextureOptimization = TextureOptimization;
  77853. /**
  77854. * Defines an optimization used to increase or decrease the rendering resolution
  77855. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77856. */
  77857. var HardwareScalingOptimization = /** @class */ (function (_super) {
  77858. __extends(HardwareScalingOptimization, _super);
  77859. /**
  77860. * Creates the HardwareScalingOptimization object
  77861. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77862. * @param maximumScale defines the maximum scale to use (2 by default)
  77863. * @param step defines the step to use between two passes (0.5 by default)
  77864. */
  77865. function HardwareScalingOptimization(
  77866. /**
  77867. * Defines the priority of this optimization (0 by default which means first in the list)
  77868. */
  77869. priority,
  77870. /**
  77871. * Defines the maximum scale to use (2 by default)
  77872. */
  77873. maximumScale,
  77874. /**
  77875. * Defines the step to use between two passes (0.5 by default)
  77876. */
  77877. step) {
  77878. if (priority === void 0) { priority = 0; }
  77879. if (maximumScale === void 0) { maximumScale = 2; }
  77880. if (step === void 0) { step = 0.25; }
  77881. var _this = _super.call(this, priority) || this;
  77882. _this.priority = priority;
  77883. _this.maximumScale = maximumScale;
  77884. _this.step = step;
  77885. _this._currentScale = -1;
  77886. _this._directionOffset = 1;
  77887. return _this;
  77888. }
  77889. /**
  77890. * Gets a string describing the action executed by the current optimization
  77891. * @return description string
  77892. */
  77893. HardwareScalingOptimization.prototype.getDescription = function () {
  77894. return "Setting hardware scaling level to " + this._currentScale;
  77895. };
  77896. /**
  77897. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77898. * @param scene defines the current scene where to apply this optimization
  77899. * @param optimizer defines the current optimizer
  77900. * @returns true if everything that can be done was applied
  77901. */
  77902. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  77903. if (this._currentScale === -1) {
  77904. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  77905. if (this._currentScale > this.maximumScale) {
  77906. this._directionOffset = -1;
  77907. }
  77908. }
  77909. this._currentScale += this._directionOffset * this.step;
  77910. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  77911. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  77912. };
  77913. ;
  77914. return HardwareScalingOptimization;
  77915. }(SceneOptimization));
  77916. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  77917. /**
  77918. * Defines an optimization used to remove shadows
  77919. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77920. */
  77921. var ShadowsOptimization = /** @class */ (function (_super) {
  77922. __extends(ShadowsOptimization, _super);
  77923. function ShadowsOptimization() {
  77924. return _super !== null && _super.apply(this, arguments) || this;
  77925. }
  77926. /**
  77927. * Gets a string describing the action executed by the current optimization
  77928. * @return description string
  77929. */
  77930. ShadowsOptimization.prototype.getDescription = function () {
  77931. return "Turning shadows on/off";
  77932. };
  77933. /**
  77934. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77935. * @param scene defines the current scene where to apply this optimization
  77936. * @param optimizer defines the current optimizer
  77937. * @returns true if everything that can be done was applied
  77938. */
  77939. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  77940. scene.shadowsEnabled = optimizer.isInImprovementMode;
  77941. return true;
  77942. };
  77943. ;
  77944. return ShadowsOptimization;
  77945. }(SceneOptimization));
  77946. BABYLON.ShadowsOptimization = ShadowsOptimization;
  77947. /**
  77948. * Defines an optimization used to turn post-processes off
  77949. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77950. */
  77951. var PostProcessesOptimization = /** @class */ (function (_super) {
  77952. __extends(PostProcessesOptimization, _super);
  77953. function PostProcessesOptimization() {
  77954. return _super !== null && _super.apply(this, arguments) || this;
  77955. }
  77956. /**
  77957. * Gets a string describing the action executed by the current optimization
  77958. * @return description string
  77959. */
  77960. PostProcessesOptimization.prototype.getDescription = function () {
  77961. return "Turning post-processes on/off";
  77962. };
  77963. /**
  77964. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77965. * @param scene defines the current scene where to apply this optimization
  77966. * @param optimizer defines the current optimizer
  77967. * @returns true if everything that can be done was applied
  77968. */
  77969. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  77970. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  77971. return true;
  77972. };
  77973. ;
  77974. return PostProcessesOptimization;
  77975. }(SceneOptimization));
  77976. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  77977. /**
  77978. * Defines an optimization used to turn lens flares off
  77979. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77980. */
  77981. var LensFlaresOptimization = /** @class */ (function (_super) {
  77982. __extends(LensFlaresOptimization, _super);
  77983. function LensFlaresOptimization() {
  77984. return _super !== null && _super.apply(this, arguments) || this;
  77985. }
  77986. /**
  77987. * Gets a string describing the action executed by the current optimization
  77988. * @return description string
  77989. */
  77990. LensFlaresOptimization.prototype.getDescription = function () {
  77991. return "Turning lens flares on/off";
  77992. };
  77993. /**
  77994. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77995. * @param scene defines the current scene where to apply this optimization
  77996. * @param optimizer defines the current optimizer
  77997. * @returns true if everything that can be done was applied
  77998. */
  77999. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  78000. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  78001. return true;
  78002. };
  78003. ;
  78004. return LensFlaresOptimization;
  78005. }(SceneOptimization));
  78006. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  78007. /**
  78008. * Defines an optimization based on user defined callback.
  78009. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78010. */
  78011. var CustomOptimization = /** @class */ (function (_super) {
  78012. __extends(CustomOptimization, _super);
  78013. function CustomOptimization() {
  78014. return _super !== null && _super.apply(this, arguments) || this;
  78015. }
  78016. /**
  78017. * Gets a string describing the action executed by the current optimization
  78018. * @returns description string
  78019. */
  78020. CustomOptimization.prototype.getDescription = function () {
  78021. if (this.onGetDescription) {
  78022. return this.onGetDescription();
  78023. }
  78024. return "Running user defined callback";
  78025. };
  78026. /**
  78027. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78028. * @param scene defines the current scene where to apply this optimization
  78029. * @param optimizer defines the current optimizer
  78030. * @returns true if everything that can be done was applied
  78031. */
  78032. CustomOptimization.prototype.apply = function (scene, optimizer) {
  78033. if (this.onApply) {
  78034. return this.onApply(scene, optimizer);
  78035. }
  78036. return true;
  78037. };
  78038. ;
  78039. return CustomOptimization;
  78040. }(SceneOptimization));
  78041. BABYLON.CustomOptimization = CustomOptimization;
  78042. /**
  78043. * Defines an optimization used to turn particles off
  78044. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78045. */
  78046. var ParticlesOptimization = /** @class */ (function (_super) {
  78047. __extends(ParticlesOptimization, _super);
  78048. function ParticlesOptimization() {
  78049. return _super !== null && _super.apply(this, arguments) || this;
  78050. }
  78051. /**
  78052. * Gets a string describing the action executed by the current optimization
  78053. * @return description string
  78054. */
  78055. ParticlesOptimization.prototype.getDescription = function () {
  78056. return "Turning particles on/off";
  78057. };
  78058. /**
  78059. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78060. * @param scene defines the current scene where to apply this optimization
  78061. * @param optimizer defines the current optimizer
  78062. * @returns true if everything that can be done was applied
  78063. */
  78064. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  78065. scene.particlesEnabled = optimizer.isInImprovementMode;
  78066. return true;
  78067. };
  78068. ;
  78069. return ParticlesOptimization;
  78070. }(SceneOptimization));
  78071. BABYLON.ParticlesOptimization = ParticlesOptimization;
  78072. /**
  78073. * Defines an optimization used to turn render targets off
  78074. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78075. */
  78076. var RenderTargetsOptimization = /** @class */ (function (_super) {
  78077. __extends(RenderTargetsOptimization, _super);
  78078. function RenderTargetsOptimization() {
  78079. return _super !== null && _super.apply(this, arguments) || this;
  78080. }
  78081. /**
  78082. * Gets a string describing the action executed by the current optimization
  78083. * @return description string
  78084. */
  78085. RenderTargetsOptimization.prototype.getDescription = function () {
  78086. return "Turning render targets off";
  78087. };
  78088. /**
  78089. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78090. * @param scene defines the current scene where to apply this optimization
  78091. * @param optimizer defines the current optimizer
  78092. * @returns true if everything that can be done was applied
  78093. */
  78094. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  78095. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  78096. return true;
  78097. };
  78098. ;
  78099. return RenderTargetsOptimization;
  78100. }(SceneOptimization));
  78101. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  78102. /**
  78103. * Defines an optimization used to merge meshes with compatible materials
  78104. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78105. */
  78106. var MergeMeshesOptimization = /** @class */ (function (_super) {
  78107. __extends(MergeMeshesOptimization, _super);
  78108. function MergeMeshesOptimization() {
  78109. var _this = _super !== null && _super.apply(this, arguments) || this;
  78110. _this._canBeMerged = function (abstractMesh) {
  78111. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  78112. return false;
  78113. }
  78114. var mesh = abstractMesh;
  78115. if (!mesh.isVisible || !mesh.isEnabled()) {
  78116. return false;
  78117. }
  78118. if (mesh.instances.length > 0) {
  78119. return false;
  78120. }
  78121. if (mesh.skeleton || mesh.hasLODLevels) {
  78122. return false;
  78123. }
  78124. if (mesh.parent) {
  78125. return false;
  78126. }
  78127. return true;
  78128. };
  78129. return _this;
  78130. }
  78131. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  78132. /**
  78133. * Gets or sets a boolean which defines if optimization octree has to be updated
  78134. */
  78135. get: function () {
  78136. return MergeMeshesOptimization._UpdateSelectionTree;
  78137. },
  78138. /**
  78139. * Gets or sets a boolean which defines if optimization octree has to be updated
  78140. */
  78141. set: function (value) {
  78142. MergeMeshesOptimization._UpdateSelectionTree = value;
  78143. },
  78144. enumerable: true,
  78145. configurable: true
  78146. });
  78147. /**
  78148. * Gets a string describing the action executed by the current optimization
  78149. * @return description string
  78150. */
  78151. MergeMeshesOptimization.prototype.getDescription = function () {
  78152. return "Merging similar meshes together";
  78153. };
  78154. /**
  78155. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78156. * @param scene defines the current scene where to apply this optimization
  78157. * @param optimizer defines the current optimizer
  78158. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  78159. * @returns true if everything that can be done was applied
  78160. */
  78161. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  78162. var globalPool = scene.meshes.slice(0);
  78163. var globalLength = globalPool.length;
  78164. for (var index = 0; index < globalLength; index++) {
  78165. var currentPool = new Array();
  78166. var current = globalPool[index];
  78167. // Checks
  78168. if (!this._canBeMerged(current)) {
  78169. continue;
  78170. }
  78171. currentPool.push(current);
  78172. // Find compatible meshes
  78173. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  78174. var otherMesh = globalPool[subIndex];
  78175. if (!this._canBeMerged(otherMesh)) {
  78176. continue;
  78177. }
  78178. if (otherMesh.material !== current.material) {
  78179. continue;
  78180. }
  78181. if (otherMesh.checkCollisions !== current.checkCollisions) {
  78182. continue;
  78183. }
  78184. currentPool.push(otherMesh);
  78185. globalLength--;
  78186. globalPool.splice(subIndex, 1);
  78187. subIndex--;
  78188. }
  78189. if (currentPool.length < 2) {
  78190. continue;
  78191. }
  78192. // Merge meshes
  78193. BABYLON.Mesh.MergeMeshes(currentPool);
  78194. }
  78195. if (updateSelectionTree != undefined) {
  78196. if (updateSelectionTree) {
  78197. scene.createOrUpdateSelectionOctree();
  78198. }
  78199. }
  78200. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  78201. scene.createOrUpdateSelectionOctree();
  78202. }
  78203. return true;
  78204. };
  78205. ;
  78206. MergeMeshesOptimization._UpdateSelectionTree = false;
  78207. return MergeMeshesOptimization;
  78208. }(SceneOptimization));
  78209. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  78210. /**
  78211. * Defines a list of options used by SceneOptimizer
  78212. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78213. */
  78214. var SceneOptimizerOptions = /** @class */ (function () {
  78215. /**
  78216. * Creates a new list of options used by SceneOptimizer
  78217. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  78218. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  78219. */
  78220. function SceneOptimizerOptions(
  78221. /**
  78222. * Defines the target frame rate to reach (60 by default)
  78223. */
  78224. targetFrameRate,
  78225. /**
  78226. * Defines the interval between two checkes (2000ms by default)
  78227. */
  78228. trackerDuration) {
  78229. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  78230. if (trackerDuration === void 0) { trackerDuration = 2000; }
  78231. this.targetFrameRate = targetFrameRate;
  78232. this.trackerDuration = trackerDuration;
  78233. /**
  78234. * Gets the list of optimizations to apply
  78235. */
  78236. this.optimizations = new Array();
  78237. }
  78238. /**
  78239. * Add a new optimization
  78240. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  78241. * @returns the current SceneOptimizerOptions
  78242. */
  78243. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  78244. this.optimizations.push(optimization);
  78245. return this;
  78246. };
  78247. /**
  78248. * Add a new custom optimization
  78249. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  78250. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  78251. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78252. * @returns the current SceneOptimizerOptions
  78253. */
  78254. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  78255. if (priority === void 0) { priority = 0; }
  78256. var optimization = new CustomOptimization(priority);
  78257. optimization.onApply = onApply;
  78258. optimization.onGetDescription = onGetDescription;
  78259. this.optimizations.push(optimization);
  78260. return this;
  78261. };
  78262. /**
  78263. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  78264. * @param targetFrameRate defines the target frame rate (60 by default)
  78265. * @returns a SceneOptimizerOptions object
  78266. */
  78267. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  78268. var result = new SceneOptimizerOptions(targetFrameRate);
  78269. var priority = 0;
  78270. result.addOptimization(new MergeMeshesOptimization(priority));
  78271. result.addOptimization(new ShadowsOptimization(priority));
  78272. result.addOptimization(new LensFlaresOptimization(priority));
  78273. // Next priority
  78274. priority++;
  78275. result.addOptimization(new PostProcessesOptimization(priority));
  78276. result.addOptimization(new ParticlesOptimization(priority));
  78277. // Next priority
  78278. priority++;
  78279. result.addOptimization(new TextureOptimization(priority, 1024));
  78280. return result;
  78281. };
  78282. /**
  78283. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  78284. * @param targetFrameRate defines the target frame rate (60 by default)
  78285. * @returns a SceneOptimizerOptions object
  78286. */
  78287. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  78288. var result = new SceneOptimizerOptions(targetFrameRate);
  78289. var priority = 0;
  78290. result.addOptimization(new MergeMeshesOptimization(priority));
  78291. result.addOptimization(new ShadowsOptimization(priority));
  78292. result.addOptimization(new LensFlaresOptimization(priority));
  78293. // Next priority
  78294. priority++;
  78295. result.addOptimization(new PostProcessesOptimization(priority));
  78296. result.addOptimization(new ParticlesOptimization(priority));
  78297. // Next priority
  78298. priority++;
  78299. result.addOptimization(new TextureOptimization(priority, 512));
  78300. // Next priority
  78301. priority++;
  78302. result.addOptimization(new RenderTargetsOptimization(priority));
  78303. // Next priority
  78304. priority++;
  78305. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  78306. return result;
  78307. };
  78308. /**
  78309. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  78310. * @param targetFrameRate defines the target frame rate (60 by default)
  78311. * @returns a SceneOptimizerOptions object
  78312. */
  78313. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  78314. var result = new SceneOptimizerOptions(targetFrameRate);
  78315. var priority = 0;
  78316. result.addOptimization(new MergeMeshesOptimization(priority));
  78317. result.addOptimization(new ShadowsOptimization(priority));
  78318. result.addOptimization(new LensFlaresOptimization(priority));
  78319. // Next priority
  78320. priority++;
  78321. result.addOptimization(new PostProcessesOptimization(priority));
  78322. result.addOptimization(new ParticlesOptimization(priority));
  78323. // Next priority
  78324. priority++;
  78325. result.addOptimization(new TextureOptimization(priority, 256));
  78326. // Next priority
  78327. priority++;
  78328. result.addOptimization(new RenderTargetsOptimization(priority));
  78329. // Next priority
  78330. priority++;
  78331. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  78332. return result;
  78333. };
  78334. return SceneOptimizerOptions;
  78335. }());
  78336. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  78337. /**
  78338. * Class used to run optimizations in order to reach a target frame rate
  78339. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78340. */
  78341. var SceneOptimizer = /** @class */ (function () {
  78342. /**
  78343. * Creates a new SceneOptimizer
  78344. * @param scene defines the scene to work on
  78345. * @param options defines the options to use with the SceneOptimizer
  78346. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  78347. * @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)
  78348. */
  78349. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  78350. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  78351. if (improvementMode === void 0) { improvementMode = false; }
  78352. var _this = this;
  78353. this._isRunning = false;
  78354. this._currentPriorityLevel = 0;
  78355. this._targetFrameRate = 60;
  78356. this._trackerDuration = 2000;
  78357. this._currentFrameRate = 0;
  78358. this._improvementMode = false;
  78359. /**
  78360. * Defines an observable called when the optimizer reaches the target frame rate
  78361. */
  78362. this.onSuccessObservable = new BABYLON.Observable();
  78363. /**
  78364. * Defines an observable called when the optimizer enables an optimization
  78365. */
  78366. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  78367. /**
  78368. * Defines an observable called when the optimizer is not able to reach the target frame rate
  78369. */
  78370. this.onFailureObservable = new BABYLON.Observable();
  78371. if (!options) {
  78372. this._options = new SceneOptimizerOptions();
  78373. }
  78374. else {
  78375. this._options = options;
  78376. }
  78377. if (this._options.targetFrameRate) {
  78378. this._targetFrameRate = this._options.targetFrameRate;
  78379. }
  78380. if (this._options.trackerDuration) {
  78381. this._trackerDuration = this._options.trackerDuration;
  78382. }
  78383. if (autoGeneratePriorities) {
  78384. var priority = 0;
  78385. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  78386. var optim = _a[_i];
  78387. optim.priority = priority++;
  78388. }
  78389. }
  78390. this._improvementMode = improvementMode;
  78391. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78392. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  78393. _this._sceneDisposeObserver = null;
  78394. _this.dispose();
  78395. });
  78396. }
  78397. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  78398. /**
  78399. * Gets a boolean indicating if the optimizer is in improvement mode
  78400. */
  78401. get: function () {
  78402. return this._improvementMode;
  78403. },
  78404. enumerable: true,
  78405. configurable: true
  78406. });
  78407. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  78408. /**
  78409. * Gets the current priority level (0 at start)
  78410. */
  78411. get: function () {
  78412. return this._currentPriorityLevel;
  78413. },
  78414. enumerable: true,
  78415. configurable: true
  78416. });
  78417. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  78418. /**
  78419. * Gets the current frame rate checked by the SceneOptimizer
  78420. */
  78421. get: function () {
  78422. return this._currentFrameRate;
  78423. },
  78424. enumerable: true,
  78425. configurable: true
  78426. });
  78427. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  78428. /**
  78429. * Gets or sets the current target frame rate (60 by default)
  78430. */
  78431. get: function () {
  78432. return this._targetFrameRate;
  78433. },
  78434. /**
  78435. * Gets or sets the current target frame rate (60 by default)
  78436. */
  78437. set: function (value) {
  78438. this._targetFrameRate = value;
  78439. },
  78440. enumerable: true,
  78441. configurable: true
  78442. });
  78443. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  78444. /**
  78445. * Gets or sets the current interval between two checks (every 2000ms by default)
  78446. */
  78447. get: function () {
  78448. return this._trackerDuration;
  78449. },
  78450. /**
  78451. * Gets or sets the current interval between two checks (every 2000ms by default)
  78452. */
  78453. set: function (value) {
  78454. this._trackerDuration = value;
  78455. },
  78456. enumerable: true,
  78457. configurable: true
  78458. });
  78459. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  78460. /**
  78461. * Gets the list of active optimizations
  78462. */
  78463. get: function () {
  78464. return this._options.optimizations;
  78465. },
  78466. enumerable: true,
  78467. configurable: true
  78468. });
  78469. /**
  78470. * Stops the current optimizer
  78471. */
  78472. SceneOptimizer.prototype.stop = function () {
  78473. this._isRunning = false;
  78474. };
  78475. /**
  78476. * Reset the optimizer to initial step (current priority level = 0)
  78477. */
  78478. SceneOptimizer.prototype.reset = function () {
  78479. this._currentPriorityLevel = 0;
  78480. };
  78481. /**
  78482. * Start the optimizer. By default it will try to reach a specific framerate
  78483. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  78484. */
  78485. SceneOptimizer.prototype.start = function () {
  78486. var _this = this;
  78487. if (this._isRunning) {
  78488. return;
  78489. }
  78490. this._isRunning = true;
  78491. // Let's wait for the scene to be ready before running our check
  78492. this._scene.executeWhenReady(function () {
  78493. setTimeout(function () {
  78494. _this._checkCurrentState();
  78495. }, _this._trackerDuration);
  78496. });
  78497. };
  78498. SceneOptimizer.prototype._checkCurrentState = function () {
  78499. var _this = this;
  78500. if (!this._isRunning) {
  78501. return;
  78502. }
  78503. var scene = this._scene;
  78504. var options = this._options;
  78505. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  78506. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  78507. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  78508. this._isRunning = false;
  78509. this.onSuccessObservable.notifyObservers(this);
  78510. return;
  78511. }
  78512. // Apply current level of optimizations
  78513. var allDone = true;
  78514. var noOptimizationApplied = true;
  78515. for (var index = 0; index < options.optimizations.length; index++) {
  78516. var optimization = options.optimizations[index];
  78517. if (optimization.priority === this._currentPriorityLevel) {
  78518. noOptimizationApplied = false;
  78519. allDone = allDone && optimization.apply(scene, this);
  78520. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  78521. }
  78522. }
  78523. // If no optimization was applied, this is a failure :(
  78524. if (noOptimizationApplied) {
  78525. this._isRunning = false;
  78526. this.onFailureObservable.notifyObservers(this);
  78527. return;
  78528. }
  78529. // If all optimizations were done, move to next level
  78530. if (allDone) {
  78531. this._currentPriorityLevel++;
  78532. }
  78533. // Let's the system running for a specific amount of time before checking FPS
  78534. scene.executeWhenReady(function () {
  78535. setTimeout(function () {
  78536. _this._checkCurrentState();
  78537. }, _this._trackerDuration);
  78538. });
  78539. };
  78540. /**
  78541. * Release all resources
  78542. */
  78543. SceneOptimizer.prototype.dispose = function () {
  78544. this.stop();
  78545. this.onSuccessObservable.clear();
  78546. this.onFailureObservable.clear();
  78547. this.onNewOptimizationAppliedObservable.clear();
  78548. if (this._sceneDisposeObserver) {
  78549. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  78550. }
  78551. };
  78552. /**
  78553. * Helper function to create a SceneOptimizer with one single line of code
  78554. * @param scene defines the scene to work on
  78555. * @param options defines the options to use with the SceneOptimizer
  78556. * @param onSuccess defines a callback to call on success
  78557. * @param onFailure defines a callback to call on failure
  78558. * @returns the new SceneOptimizer object
  78559. */
  78560. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  78561. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  78562. if (onSuccess) {
  78563. optimizer.onSuccessObservable.add(function () {
  78564. onSuccess();
  78565. });
  78566. }
  78567. if (onFailure) {
  78568. optimizer.onFailureObservable.add(function () {
  78569. onFailure();
  78570. });
  78571. }
  78572. optimizer.start();
  78573. return optimizer;
  78574. };
  78575. return SceneOptimizer;
  78576. }());
  78577. BABYLON.SceneOptimizer = SceneOptimizer;
  78578. })(BABYLON || (BABYLON = {}));
  78579. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  78580. var BABYLON;
  78581. (function (BABYLON) {
  78582. var OutlineRenderer = /** @class */ (function () {
  78583. function OutlineRenderer(scene) {
  78584. this.zOffset = 1;
  78585. this._scene = scene;
  78586. }
  78587. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  78588. var _this = this;
  78589. if (useOverlay === void 0) { useOverlay = false; }
  78590. var scene = this._scene;
  78591. var engine = this._scene.getEngine();
  78592. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78593. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  78594. return;
  78595. }
  78596. var mesh = subMesh.getRenderingMesh();
  78597. var material = subMesh.getMaterial();
  78598. if (!material || !scene.activeCamera) {
  78599. return;
  78600. }
  78601. engine.enableEffect(this._effect);
  78602. // Logarithmic depth
  78603. if (material.useLogarithmicDepth) {
  78604. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  78605. }
  78606. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  78607. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78608. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78609. // Bones
  78610. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78611. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78612. }
  78613. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78614. // Alpha test
  78615. if (material && material.needAlphaTesting()) {
  78616. var alphaTexture = material.getAlphaTestTexture();
  78617. if (alphaTexture) {
  78618. this._effect.setTexture("diffuseSampler", alphaTexture);
  78619. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78620. }
  78621. }
  78622. engine.setZOffset(-this.zOffset);
  78623. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78624. engine.setZOffset(0);
  78625. };
  78626. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78627. var defines = [];
  78628. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78629. var mesh = subMesh.getMesh();
  78630. var material = subMesh.getMaterial();
  78631. if (material) {
  78632. // Alpha test
  78633. if (material.needAlphaTesting()) {
  78634. defines.push("#define ALPHATEST");
  78635. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78636. attribs.push(BABYLON.VertexBuffer.UVKind);
  78637. defines.push("#define UV1");
  78638. }
  78639. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78640. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78641. defines.push("#define UV2");
  78642. }
  78643. }
  78644. //Logarithmic depth
  78645. if (material.useLogarithmicDepth) {
  78646. defines.push("#define LOGARITHMICDEPTH");
  78647. }
  78648. }
  78649. // Bones
  78650. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78651. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78652. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78653. if (mesh.numBoneInfluencers > 4) {
  78654. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78655. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78656. }
  78657. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78658. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78659. }
  78660. else {
  78661. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78662. }
  78663. // Instances
  78664. if (useInstances) {
  78665. defines.push("#define INSTANCES");
  78666. attribs.push("world0");
  78667. attribs.push("world1");
  78668. attribs.push("world2");
  78669. attribs.push("world3");
  78670. }
  78671. // Get correct effect
  78672. var join = defines.join("\n");
  78673. if (this._cachedDefines !== join) {
  78674. this._cachedDefines = join;
  78675. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  78676. }
  78677. return this._effect.isReady();
  78678. };
  78679. return OutlineRenderer;
  78680. }());
  78681. BABYLON.OutlineRenderer = OutlineRenderer;
  78682. })(BABYLON || (BABYLON = {}));
  78683. //# sourceMappingURL=babylon.outlineRenderer.js.map
  78684. var BABYLON;
  78685. (function (BABYLON) {
  78686. var FaceAdjacencies = /** @class */ (function () {
  78687. function FaceAdjacencies() {
  78688. this.edges = new Array();
  78689. this.edgesConnectedCount = 0;
  78690. }
  78691. return FaceAdjacencies;
  78692. }());
  78693. var EdgesRenderer = /** @class */ (function () {
  78694. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  78695. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  78696. if (epsilon === void 0) { epsilon = 0.95; }
  78697. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  78698. this.edgesWidthScalerForOrthographic = 1000.0;
  78699. this.edgesWidthScalerForPerspective = 50.0;
  78700. this._linesPositions = new Array();
  78701. this._linesNormals = new Array();
  78702. this._linesIndices = new Array();
  78703. this._buffers = {};
  78704. this._checkVerticesInsteadOfIndices = false;
  78705. this._source = source;
  78706. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  78707. this._epsilon = epsilon;
  78708. this._prepareRessources();
  78709. this._generateEdgesLines();
  78710. }
  78711. EdgesRenderer.prototype._prepareRessources = function () {
  78712. if (this._lineShader) {
  78713. return;
  78714. }
  78715. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  78716. attributes: ["position", "normal"],
  78717. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  78718. });
  78719. this._lineShader.disableDepthWrite = true;
  78720. this._lineShader.backFaceCulling = false;
  78721. };
  78722. EdgesRenderer.prototype._rebuild = function () {
  78723. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78724. if (buffer) {
  78725. buffer._rebuild();
  78726. }
  78727. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78728. if (buffer) {
  78729. buffer._rebuild();
  78730. }
  78731. var scene = this._source.getScene();
  78732. var engine = scene.getEngine();
  78733. this._ib = engine.createIndexBuffer(this._linesIndices);
  78734. };
  78735. EdgesRenderer.prototype.dispose = function () {
  78736. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78737. if (buffer) {
  78738. buffer.dispose();
  78739. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  78740. }
  78741. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78742. if (buffer) {
  78743. buffer.dispose();
  78744. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  78745. }
  78746. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  78747. this._lineShader.dispose();
  78748. };
  78749. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  78750. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  78751. return 0;
  78752. }
  78753. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  78754. return 1;
  78755. }
  78756. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  78757. return 2;
  78758. }
  78759. return -1;
  78760. };
  78761. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  78762. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  78763. return 0;
  78764. }
  78765. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  78766. return 1;
  78767. }
  78768. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  78769. return 2;
  78770. }
  78771. return -1;
  78772. };
  78773. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  78774. var needToCreateLine;
  78775. if (edge === undefined) {
  78776. needToCreateLine = true;
  78777. }
  78778. else {
  78779. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  78780. needToCreateLine = dotProduct < this._epsilon;
  78781. }
  78782. if (needToCreateLine) {
  78783. var offset = this._linesPositions.length / 3;
  78784. var normal = p0.subtract(p1);
  78785. normal.normalize();
  78786. // Positions
  78787. this._linesPositions.push(p0.x);
  78788. this._linesPositions.push(p0.y);
  78789. this._linesPositions.push(p0.z);
  78790. this._linesPositions.push(p0.x);
  78791. this._linesPositions.push(p0.y);
  78792. this._linesPositions.push(p0.z);
  78793. this._linesPositions.push(p1.x);
  78794. this._linesPositions.push(p1.y);
  78795. this._linesPositions.push(p1.z);
  78796. this._linesPositions.push(p1.x);
  78797. this._linesPositions.push(p1.y);
  78798. this._linesPositions.push(p1.z);
  78799. // Normals
  78800. this._linesNormals.push(p1.x);
  78801. this._linesNormals.push(p1.y);
  78802. this._linesNormals.push(p1.z);
  78803. this._linesNormals.push(-1);
  78804. this._linesNormals.push(p1.x);
  78805. this._linesNormals.push(p1.y);
  78806. this._linesNormals.push(p1.z);
  78807. this._linesNormals.push(1);
  78808. this._linesNormals.push(p0.x);
  78809. this._linesNormals.push(p0.y);
  78810. this._linesNormals.push(p0.z);
  78811. this._linesNormals.push(-1);
  78812. this._linesNormals.push(p0.x);
  78813. this._linesNormals.push(p0.y);
  78814. this._linesNormals.push(p0.z);
  78815. this._linesNormals.push(1);
  78816. // Indices
  78817. this._linesIndices.push(offset);
  78818. this._linesIndices.push(offset + 1);
  78819. this._linesIndices.push(offset + 2);
  78820. this._linesIndices.push(offset);
  78821. this._linesIndices.push(offset + 2);
  78822. this._linesIndices.push(offset + 3);
  78823. }
  78824. };
  78825. EdgesRenderer.prototype._generateEdgesLines = function () {
  78826. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78827. var indices = this._source.getIndices();
  78828. if (!indices || !positions) {
  78829. return;
  78830. }
  78831. // First let's find adjacencies
  78832. var adjacencies = new Array();
  78833. var faceNormals = new Array();
  78834. var index;
  78835. var faceAdjacencies;
  78836. // Prepare faces
  78837. for (index = 0; index < indices.length; index += 3) {
  78838. faceAdjacencies = new FaceAdjacencies();
  78839. var p0Index = indices[index];
  78840. var p1Index = indices[index + 1];
  78841. var p2Index = indices[index + 2];
  78842. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  78843. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  78844. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  78845. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  78846. faceNormal.normalize();
  78847. faceNormals.push(faceNormal);
  78848. adjacencies.push(faceAdjacencies);
  78849. }
  78850. // Scan
  78851. for (index = 0; index < adjacencies.length; index++) {
  78852. faceAdjacencies = adjacencies[index];
  78853. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  78854. var otherFaceAdjacencies = adjacencies[otherIndex];
  78855. if (faceAdjacencies.edgesConnectedCount === 3) {
  78856. break;
  78857. }
  78858. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  78859. continue;
  78860. }
  78861. var otherP0 = indices[otherIndex * 3];
  78862. var otherP1 = indices[otherIndex * 3 + 1];
  78863. var otherP2 = indices[otherIndex * 3 + 2];
  78864. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  78865. var otherEdgeIndex = 0;
  78866. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  78867. continue;
  78868. }
  78869. switch (edgeIndex) {
  78870. case 0:
  78871. if (this._checkVerticesInsteadOfIndices) {
  78872. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78873. }
  78874. else {
  78875. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  78876. }
  78877. break;
  78878. case 1:
  78879. if (this._checkVerticesInsteadOfIndices) {
  78880. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78881. }
  78882. else {
  78883. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  78884. }
  78885. break;
  78886. case 2:
  78887. if (this._checkVerticesInsteadOfIndices) {
  78888. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78889. }
  78890. else {
  78891. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  78892. }
  78893. break;
  78894. }
  78895. if (otherEdgeIndex === -1) {
  78896. continue;
  78897. }
  78898. faceAdjacencies.edges[edgeIndex] = otherIndex;
  78899. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  78900. faceAdjacencies.edgesConnectedCount++;
  78901. otherFaceAdjacencies.edgesConnectedCount++;
  78902. if (faceAdjacencies.edgesConnectedCount === 3) {
  78903. break;
  78904. }
  78905. }
  78906. }
  78907. }
  78908. // Create lines
  78909. for (index = 0; index < adjacencies.length; index++) {
  78910. // 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
  78911. var current = adjacencies[index];
  78912. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  78913. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  78914. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  78915. }
  78916. // Merge into a single mesh
  78917. var engine = this._source.getScene().getEngine();
  78918. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  78919. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  78920. this._ib = engine.createIndexBuffer(this._linesIndices);
  78921. this._indicesCount = this._linesIndices.length;
  78922. };
  78923. EdgesRenderer.prototype.render = function () {
  78924. var scene = this._source.getScene();
  78925. if (!this._lineShader.isReady() || !scene.activeCamera) {
  78926. return;
  78927. }
  78928. var engine = scene.getEngine();
  78929. this._lineShader._preBind();
  78930. // VBOs
  78931. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  78932. scene.resetCachedMaterial();
  78933. this._lineShader.setColor4("color", this._source.edgesColor);
  78934. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  78935. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  78936. }
  78937. else {
  78938. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  78939. }
  78940. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  78941. this._lineShader.bind(this._source.getWorldMatrix());
  78942. // Draw order
  78943. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  78944. this._lineShader.unbind();
  78945. engine.setDepthWrite(true);
  78946. };
  78947. return EdgesRenderer;
  78948. }());
  78949. BABYLON.EdgesRenderer = EdgesRenderer;
  78950. })(BABYLON || (BABYLON = {}));
  78951. //# sourceMappingURL=babylon.edgesRenderer.js.map
  78952. var BABYLON;
  78953. (function (BABYLON) {
  78954. /**
  78955. * Special Glow Blur post process only blurring the alpha channel
  78956. * It enforces keeping the most luminous color in the color channel.
  78957. */
  78958. var GlowBlurPostProcess = /** @class */ (function (_super) {
  78959. __extends(GlowBlurPostProcess, _super);
  78960. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  78961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78962. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  78963. _this.direction = direction;
  78964. _this.kernel = kernel;
  78965. _this.onApplyObservable.add(function (effect) {
  78966. effect.setFloat2("screenSize", _this.width, _this.height);
  78967. effect.setVector2("direction", _this.direction);
  78968. effect.setFloat("blurWidth", _this.kernel);
  78969. });
  78970. return _this;
  78971. }
  78972. return GlowBlurPostProcess;
  78973. }(BABYLON.PostProcess));
  78974. /**
  78975. * The highlight layer Helps adding a glow effect around a mesh.
  78976. *
  78977. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  78978. * glowy meshes to your scene.
  78979. *
  78980. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  78981. */
  78982. var HighlightLayer = /** @class */ (function () {
  78983. /**
  78984. * Instantiates a new highlight Layer and references it to the scene..
  78985. * @param name The name of the layer
  78986. * @param scene The scene to use the layer in
  78987. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  78988. */
  78989. function HighlightLayer(name, scene, options) {
  78990. this.name = name;
  78991. this._vertexBuffers = {};
  78992. this._mainTextureDesiredSize = { width: 0, height: 0 };
  78993. this._meshes = {};
  78994. this._maxSize = 0;
  78995. this._shouldRender = false;
  78996. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  78997. this._excludedMeshes = {};
  78998. /**
  78999. * Specifies whether or not the inner glow is ACTIVE in the layer.
  79000. */
  79001. this.innerGlow = true;
  79002. /**
  79003. * Specifies whether or not the outer glow is ACTIVE in the layer.
  79004. */
  79005. this.outerGlow = true;
  79006. /**
  79007. * Specifies wether the highlight layer is enabled or not.
  79008. */
  79009. this.isEnabled = true;
  79010. /**
  79011. * An event triggered when the highlight layer has been disposed.
  79012. * @type {BABYLON.Observable}
  79013. */
  79014. this.onDisposeObservable = new BABYLON.Observable();
  79015. /**
  79016. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  79017. * @type {BABYLON.Observable}
  79018. */
  79019. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  79020. /**
  79021. * An event triggered when the highlight layer is being blurred.
  79022. * @type {BABYLON.Observable}
  79023. */
  79024. this.onBeforeBlurObservable = new BABYLON.Observable();
  79025. /**
  79026. * An event triggered when the highlight layer has been blurred.
  79027. * @type {BABYLON.Observable}
  79028. */
  79029. this.onAfterBlurObservable = new BABYLON.Observable();
  79030. /**
  79031. * An event triggered when the glowing blurred texture is being merged in the scene.
  79032. * @type {BABYLON.Observable}
  79033. */
  79034. this.onBeforeComposeObservable = new BABYLON.Observable();
  79035. /**
  79036. * An event triggered when the glowing blurred texture has been merged in the scene.
  79037. * @type {BABYLON.Observable}
  79038. */
  79039. this.onAfterComposeObservable = new BABYLON.Observable();
  79040. /**
  79041. * An event triggered when the highlight layer changes its size.
  79042. * @type {BABYLON.Observable}
  79043. */
  79044. this.onSizeChangedObservable = new BABYLON.Observable();
  79045. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79046. var engine = scene.getEngine();
  79047. this._engine = engine;
  79048. this._maxSize = this._engine.getCaps().maxTextureSize;
  79049. this._scene.highlightLayers.push(this);
  79050. // Warn on stencil.
  79051. if (!this._engine.isStencilEnable) {
  79052. 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 }");
  79053. }
  79054. // Adapt options
  79055. this._options = options || {
  79056. mainTextureRatio: 0.5,
  79057. blurTextureSizeRatio: 0.5,
  79058. blurHorizontalSize: 1.0,
  79059. blurVerticalSize: 1.0,
  79060. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  79061. camera: null
  79062. };
  79063. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  79064. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  79065. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  79066. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  79067. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  79068. // VBO
  79069. var vertices = [];
  79070. vertices.push(1, 1);
  79071. vertices.push(-1, 1);
  79072. vertices.push(-1, -1);
  79073. vertices.push(1, -1);
  79074. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79075. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  79076. this._createIndexBuffer();
  79077. // Effect
  79078. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  79079. // Render target
  79080. this.setMainTextureSize();
  79081. // Create Textures and post processes
  79082. this.createTextureAndPostProcesses();
  79083. }
  79084. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  79085. /**
  79086. * Gets the horizontal size of the blur.
  79087. */
  79088. get: function () {
  79089. return this._horizontalBlurPostprocess.kernel;
  79090. },
  79091. /**
  79092. * Specifies the horizontal size of the blur.
  79093. */
  79094. set: function (value) {
  79095. this._horizontalBlurPostprocess.kernel = value;
  79096. },
  79097. enumerable: true,
  79098. configurable: true
  79099. });
  79100. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  79101. /**
  79102. * Gets the vertical size of the blur.
  79103. */
  79104. get: function () {
  79105. return this._verticalBlurPostprocess.kernel;
  79106. },
  79107. /**
  79108. * Specifies the vertical size of the blur.
  79109. */
  79110. set: function (value) {
  79111. this._verticalBlurPostprocess.kernel = value;
  79112. },
  79113. enumerable: true,
  79114. configurable: true
  79115. });
  79116. Object.defineProperty(HighlightLayer.prototype, "camera", {
  79117. /**
  79118. * Gets the camera attached to the layer.
  79119. */
  79120. get: function () {
  79121. return this._options.camera;
  79122. },
  79123. enumerable: true,
  79124. configurable: true
  79125. });
  79126. HighlightLayer.prototype._createIndexBuffer = function () {
  79127. var engine = this._scene.getEngine();
  79128. // Indices
  79129. var indices = [];
  79130. indices.push(0);
  79131. indices.push(1);
  79132. indices.push(2);
  79133. indices.push(0);
  79134. indices.push(2);
  79135. indices.push(3);
  79136. this._indexBuffer = engine.createIndexBuffer(indices);
  79137. };
  79138. HighlightLayer.prototype._rebuild = function () {
  79139. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79140. if (vb) {
  79141. vb._rebuild();
  79142. }
  79143. this._createIndexBuffer();
  79144. };
  79145. /**
  79146. * Creates the render target textures and post processes used in the highlight layer.
  79147. */
  79148. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  79149. var _this = this;
  79150. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  79151. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  79152. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  79153. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  79154. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  79155. width: this._mainTextureDesiredSize.width,
  79156. height: this._mainTextureDesiredSize.height
  79157. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79158. this._mainTexture.activeCamera = this._options.camera;
  79159. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79160. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79161. this._mainTexture.anisotropicFilteringLevel = 1;
  79162. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79163. this._mainTexture.renderParticles = false;
  79164. this._mainTexture.renderList = null;
  79165. this._mainTexture.ignoreCameraViewport = true;
  79166. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  79167. width: blurTextureWidth,
  79168. height: blurTextureHeight
  79169. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79170. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79171. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79172. this._blurTexture.anisotropicFilteringLevel = 16;
  79173. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79174. this._blurTexture.renderParticles = false;
  79175. this._blurTexture.ignoreCameraViewport = true;
  79176. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79177. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  79178. effect.setTexture("textureSampler", _this._mainTexture);
  79179. });
  79180. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  79181. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79182. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79183. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79184. });
  79185. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79186. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79187. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79188. });
  79189. }
  79190. else {
  79191. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79192. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79193. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79194. });
  79195. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79196. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79197. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79198. });
  79199. }
  79200. this._mainTexture.onAfterUnbindObservable.add(function () {
  79201. _this.onBeforeBlurObservable.notifyObservers(_this);
  79202. var internalTexture = _this._blurTexture.getInternalTexture();
  79203. if (internalTexture) {
  79204. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  79205. }
  79206. _this.onAfterBlurObservable.notifyObservers(_this);
  79207. });
  79208. // Custom render function
  79209. var renderSubMesh = function (subMesh) {
  79210. if (!_this._meshes) {
  79211. return;
  79212. }
  79213. var material = subMesh.getMaterial();
  79214. var mesh = subMesh.getRenderingMesh();
  79215. var scene = _this._scene;
  79216. var engine = scene.getEngine();
  79217. if (!material) {
  79218. return;
  79219. }
  79220. // Do not block in blend mode.
  79221. if (material.needAlphaBlendingForMesh(mesh)) {
  79222. return;
  79223. }
  79224. // Culling
  79225. engine.setState(material.backFaceCulling);
  79226. // Managing instances
  79227. var batch = mesh._getInstancesRenderList(subMesh._id);
  79228. if (batch.mustReturn) {
  79229. return;
  79230. }
  79231. // Excluded Mesh
  79232. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79233. return;
  79234. }
  79235. ;
  79236. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79237. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  79238. var emissiveTexture = null;
  79239. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79240. emissiveTexture = material.emissiveTexture;
  79241. }
  79242. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  79243. engine.enableEffect(_this._glowMapGenerationEffect);
  79244. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  79245. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  79246. if (highlightLayerMesh) {
  79247. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  79248. }
  79249. else {
  79250. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  79251. }
  79252. // Alpha test
  79253. if (material && material.needAlphaTesting()) {
  79254. var alphaTexture = material.getAlphaTestTexture();
  79255. if (alphaTexture) {
  79256. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  79257. var textureMatrix = alphaTexture.getTextureMatrix();
  79258. if (textureMatrix) {
  79259. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  79260. }
  79261. }
  79262. }
  79263. // Glow emissive only
  79264. if (emissiveTexture) {
  79265. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  79266. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  79267. }
  79268. // Bones
  79269. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79270. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79271. }
  79272. // Draw
  79273. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  79274. }
  79275. else {
  79276. // Need to reset refresh rate of the shadowMap
  79277. _this._mainTexture.resetRefreshCounter();
  79278. }
  79279. };
  79280. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79281. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  79282. var index;
  79283. var engine = _this._scene.getEngine();
  79284. if (depthOnlySubMeshes.length) {
  79285. engine.setColorWrite(false);
  79286. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79287. renderSubMesh(depthOnlySubMeshes.data[index]);
  79288. }
  79289. engine.setColorWrite(true);
  79290. }
  79291. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79292. renderSubMesh(opaqueSubMeshes.data[index]);
  79293. }
  79294. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79295. renderSubMesh(alphaTestSubMeshes.data[index]);
  79296. }
  79297. for (index = 0; index < transparentSubMeshes.length; index++) {
  79298. renderSubMesh(transparentSubMeshes.data[index]);
  79299. }
  79300. };
  79301. this._mainTexture.onClearObservable.add(function (engine) {
  79302. engine.clear(HighlightLayer.neutralColor, true, true, true);
  79303. });
  79304. };
  79305. /**
  79306. * Checks for the readiness of the element composing the layer.
  79307. * @param subMesh the mesh to check for
  79308. * @param useInstances specify wether or not to use instances to render the mesh
  79309. * @param emissiveTexture the associated emissive texture used to generate the glow
  79310. * @return true if ready otherwise, false
  79311. */
  79312. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  79313. var material = subMesh.getMaterial();
  79314. var mesh = subMesh.getRenderingMesh();
  79315. if (!material || !mesh || !this._meshes) {
  79316. return false;
  79317. }
  79318. var emissiveTexture = null;
  79319. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  79320. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79321. emissiveTexture = material.emissiveTexture;
  79322. }
  79323. return this._isReady(subMesh, useInstances, emissiveTexture);
  79324. };
  79325. /**
  79326. * Checks for the readiness of the element composing the layer.
  79327. * @param subMesh the mesh to check for
  79328. * @param useInstances specify wether or not to use instances to render the mesh
  79329. * @param emissiveTexture the associated emissive texture used to generate the glow
  79330. * @return true if ready otherwise, false
  79331. */
  79332. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  79333. var material = subMesh.getMaterial();
  79334. if (!material) {
  79335. return false;
  79336. }
  79337. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  79338. return false;
  79339. }
  79340. var defines = [];
  79341. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79342. var mesh = subMesh.getMesh();
  79343. var uv1 = false;
  79344. var uv2 = false;
  79345. // Alpha test
  79346. if (material && material.needAlphaTesting()) {
  79347. var alphaTexture = material.getAlphaTestTexture();
  79348. if (alphaTexture) {
  79349. defines.push("#define ALPHATEST");
  79350. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79351. alphaTexture.coordinatesIndex === 1) {
  79352. defines.push("#define DIFFUSEUV2");
  79353. uv2 = true;
  79354. }
  79355. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79356. defines.push("#define DIFFUSEUV1");
  79357. uv1 = true;
  79358. }
  79359. }
  79360. }
  79361. // Emissive
  79362. if (emissiveTexture) {
  79363. defines.push("#define EMISSIVE");
  79364. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79365. emissiveTexture.coordinatesIndex === 1) {
  79366. defines.push("#define EMISSIVEUV2");
  79367. uv2 = true;
  79368. }
  79369. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79370. defines.push("#define EMISSIVEUV1");
  79371. uv1 = true;
  79372. }
  79373. }
  79374. if (uv1) {
  79375. attribs.push(BABYLON.VertexBuffer.UVKind);
  79376. defines.push("#define UV1");
  79377. }
  79378. if (uv2) {
  79379. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79380. defines.push("#define UV2");
  79381. }
  79382. // Bones
  79383. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79384. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79385. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79386. if (mesh.numBoneInfluencers > 4) {
  79387. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79388. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79389. }
  79390. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79391. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79392. }
  79393. else {
  79394. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79395. }
  79396. // Instances
  79397. if (useInstances) {
  79398. defines.push("#define INSTANCES");
  79399. attribs.push("world0");
  79400. attribs.push("world1");
  79401. attribs.push("world2");
  79402. attribs.push("world3");
  79403. }
  79404. // Get correct effect
  79405. var join = defines.join("\n");
  79406. if (this._cachedDefines !== join) {
  79407. this._cachedDefines = join;
  79408. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  79409. }
  79410. return this._glowMapGenerationEffect.isReady();
  79411. };
  79412. /**
  79413. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  79414. */
  79415. HighlightLayer.prototype.render = function () {
  79416. var currentEffect = this._glowMapMergeEffect;
  79417. // Check
  79418. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  79419. return;
  79420. var engine = this._scene.getEngine();
  79421. this.onBeforeComposeObservable.notifyObservers(this);
  79422. // Render
  79423. engine.enableEffect(currentEffect);
  79424. engine.setState(false);
  79425. // Cache
  79426. var previousStencilBuffer = engine.getStencilBuffer();
  79427. var previousStencilFunction = engine.getStencilFunction();
  79428. var previousStencilMask = engine.getStencilMask();
  79429. var previousStencilOperationPass = engine.getStencilOperationPass();
  79430. var previousStencilOperationFail = engine.getStencilOperationFail();
  79431. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  79432. var previousAlphaMode = engine.getAlphaMode();
  79433. // Texture
  79434. currentEffect.setTexture("textureSampler", this._blurTexture);
  79435. // VBOs
  79436. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  79437. // Stencil operations
  79438. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  79439. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  79440. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  79441. // Draw order
  79442. engine.setAlphaMode(this._options.alphaBlendingMode);
  79443. engine.setStencilMask(0x00);
  79444. engine.setStencilBuffer(true);
  79445. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  79446. if (this.outerGlow) {
  79447. currentEffect.setFloat("offset", 0);
  79448. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  79449. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79450. }
  79451. if (this.innerGlow) {
  79452. currentEffect.setFloat("offset", 1);
  79453. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  79454. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79455. }
  79456. // Restore Cache
  79457. engine.setStencilFunction(previousStencilFunction);
  79458. engine.setStencilMask(previousStencilMask);
  79459. engine.setAlphaMode(previousAlphaMode);
  79460. engine.setStencilBuffer(previousStencilBuffer);
  79461. engine.setStencilOperationPass(previousStencilOperationPass);
  79462. engine.setStencilOperationFail(previousStencilOperationFail);
  79463. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  79464. engine._stencilState.reset();
  79465. this.onAfterComposeObservable.notifyObservers(this);
  79466. // Handle size changes.
  79467. var size = this._mainTexture.getSize();
  79468. this.setMainTextureSize();
  79469. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  79470. // Recreate RTT and post processes on size change.
  79471. this.onSizeChangedObservable.notifyObservers(this);
  79472. this.disposeTextureAndPostProcesses();
  79473. this.createTextureAndPostProcesses();
  79474. }
  79475. };
  79476. /**
  79477. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  79478. * @param mesh The mesh to exclude from the highlight layer
  79479. */
  79480. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  79481. if (!this._excludedMeshes) {
  79482. return;
  79483. }
  79484. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79485. if (!meshExcluded) {
  79486. this._excludedMeshes[mesh.uniqueId] = {
  79487. mesh: mesh,
  79488. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  79489. mesh.getEngine().setStencilBuffer(false);
  79490. }),
  79491. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  79492. mesh.getEngine().setStencilBuffer(true);
  79493. }),
  79494. };
  79495. }
  79496. };
  79497. /**
  79498. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  79499. * @param mesh The mesh to highlight
  79500. */
  79501. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  79502. if (!this._excludedMeshes) {
  79503. return;
  79504. }
  79505. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79506. if (meshExcluded) {
  79507. if (meshExcluded.beforeRender) {
  79508. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  79509. }
  79510. if (meshExcluded.afterRender) {
  79511. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  79512. }
  79513. }
  79514. this._excludedMeshes[mesh.uniqueId] = null;
  79515. };
  79516. /**
  79517. * Determine if a given mesh will be highlighted by the current HighlightLayer
  79518. * @param mesh mesh to test
  79519. * @returns true if the mesh will be highlighted by the current HighlightLayer
  79520. */
  79521. HighlightLayer.prototype.hasMesh = function (mesh) {
  79522. if (!this._meshes) {
  79523. return false;
  79524. }
  79525. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  79526. };
  79527. /**
  79528. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  79529. * @param mesh The mesh to highlight
  79530. * @param color The color of the highlight
  79531. * @param glowEmissiveOnly Extract the glow from the emissive texture
  79532. */
  79533. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  79534. var _this = this;
  79535. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  79536. if (!this._meshes) {
  79537. return;
  79538. }
  79539. var meshHighlight = this._meshes[mesh.uniqueId];
  79540. if (meshHighlight) {
  79541. meshHighlight.color = color;
  79542. }
  79543. else {
  79544. this._meshes[mesh.uniqueId] = {
  79545. mesh: mesh,
  79546. color: color,
  79547. // Lambda required for capture due to Observable this context
  79548. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  79549. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79550. _this.defaultStencilReference(mesh);
  79551. }
  79552. else {
  79553. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  79554. }
  79555. }),
  79556. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  79557. glowEmissiveOnly: glowEmissiveOnly
  79558. };
  79559. }
  79560. this._shouldRender = true;
  79561. };
  79562. /**
  79563. * Remove a mesh from the highlight layer in order to make it stop glowing.
  79564. * @param mesh The mesh to highlight
  79565. */
  79566. HighlightLayer.prototype.removeMesh = function (mesh) {
  79567. if (!this._meshes) {
  79568. return;
  79569. }
  79570. var meshHighlight = this._meshes[mesh.uniqueId];
  79571. if (meshHighlight) {
  79572. if (meshHighlight.observerHighlight) {
  79573. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79574. }
  79575. if (meshHighlight.observerDefault) {
  79576. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79577. }
  79578. delete this._meshes[mesh.uniqueId];
  79579. }
  79580. this._shouldRender = false;
  79581. for (var meshHighlightToCheck in this._meshes) {
  79582. if (this._meshes[meshHighlightToCheck]) {
  79583. this._shouldRender = true;
  79584. break;
  79585. }
  79586. }
  79587. };
  79588. /**
  79589. * Returns true if the layer contains information to display, otherwise false.
  79590. */
  79591. HighlightLayer.prototype.shouldRender = function () {
  79592. return this.isEnabled && this._shouldRender;
  79593. };
  79594. /**
  79595. * Sets the main texture desired size which is the closest power of two
  79596. * of the engine canvas size.
  79597. */
  79598. HighlightLayer.prototype.setMainTextureSize = function () {
  79599. if (this._options.mainTextureFixedSize) {
  79600. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  79601. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  79602. }
  79603. else {
  79604. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  79605. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  79606. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  79607. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79608. }
  79609. };
  79610. /**
  79611. * Force the stencil to the normal expected value for none glowing parts
  79612. */
  79613. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79614. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79615. };
  79616. /**
  79617. * Dispose only the render target textures and post process.
  79618. */
  79619. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79620. this._blurTexture.dispose();
  79621. this._mainTexture.dispose();
  79622. this._downSamplePostprocess.dispose();
  79623. this._horizontalBlurPostprocess.dispose();
  79624. this._verticalBlurPostprocess.dispose();
  79625. };
  79626. /**
  79627. * Dispose the highlight layer and free resources.
  79628. */
  79629. HighlightLayer.prototype.dispose = function () {
  79630. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79631. if (vertexBuffer) {
  79632. vertexBuffer.dispose();
  79633. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79634. }
  79635. if (this._indexBuffer) {
  79636. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79637. this._indexBuffer = null;
  79638. }
  79639. // Clean textures and post processes
  79640. this.disposeTextureAndPostProcesses();
  79641. if (this._meshes) {
  79642. // Clean mesh references
  79643. for (var id in this._meshes) {
  79644. var meshHighlight = this._meshes[id];
  79645. if (meshHighlight && meshHighlight.mesh) {
  79646. if (meshHighlight.observerHighlight) {
  79647. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79648. }
  79649. if (meshHighlight.observerDefault) {
  79650. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79651. }
  79652. }
  79653. }
  79654. this._meshes = null;
  79655. }
  79656. if (this._excludedMeshes) {
  79657. for (var id in this._excludedMeshes) {
  79658. var meshHighlight = this._excludedMeshes[id];
  79659. if (meshHighlight) {
  79660. if (meshHighlight.beforeRender) {
  79661. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  79662. }
  79663. if (meshHighlight.afterRender) {
  79664. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  79665. }
  79666. }
  79667. }
  79668. this._excludedMeshes = null;
  79669. }
  79670. // Remove from scene
  79671. var index = this._scene.highlightLayers.indexOf(this, 0);
  79672. if (index > -1) {
  79673. this._scene.highlightLayers.splice(index, 1);
  79674. }
  79675. // Callback
  79676. this.onDisposeObservable.notifyObservers(this);
  79677. this.onDisposeObservable.clear();
  79678. this.onBeforeRenderMainTextureObservable.clear();
  79679. this.onBeforeBlurObservable.clear();
  79680. this.onBeforeComposeObservable.clear();
  79681. this.onAfterComposeObservable.clear();
  79682. this.onSizeChangedObservable.clear();
  79683. };
  79684. /**
  79685. * The neutral color used during the preparation of the glow effect.
  79686. * This is black by default as the blend operation is a blend operation.
  79687. */
  79688. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  79689. /**
  79690. * Stencil value used for glowing meshes.
  79691. */
  79692. HighlightLayer.glowingMeshStencilReference = 0x02;
  79693. /**
  79694. * Stencil value used for the other meshes in the scene.
  79695. */
  79696. HighlightLayer.normalMeshStencilReference = 0x01;
  79697. return HighlightLayer;
  79698. }());
  79699. BABYLON.HighlightLayer = HighlightLayer;
  79700. })(BABYLON || (BABYLON = {}));
  79701. //# sourceMappingURL=babylon.highlightlayer.js.map
  79702. var BABYLON;
  79703. (function (BABYLON) {
  79704. /**
  79705. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  79706. */
  79707. var AssetTaskState;
  79708. (function (AssetTaskState) {
  79709. /**
  79710. * Initialization
  79711. */
  79712. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  79713. /**
  79714. * Running
  79715. */
  79716. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  79717. /**
  79718. * Done
  79719. */
  79720. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  79721. /**
  79722. * Error
  79723. */
  79724. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  79725. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  79726. /**
  79727. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  79728. */
  79729. var AbstractAssetTask = /** @class */ (function () {
  79730. /**
  79731. * Creates a new {BABYLON.AssetsManager}
  79732. * @param name defines the name of the task
  79733. */
  79734. function AbstractAssetTask(
  79735. /**
  79736. * Task name
  79737. */ name) {
  79738. this.name = name;
  79739. this._isCompleted = false;
  79740. this._taskState = AssetTaskState.INIT;
  79741. }
  79742. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  79743. /**
  79744. * Get if the task is completed
  79745. */
  79746. get: function () {
  79747. return this._isCompleted;
  79748. },
  79749. enumerable: true,
  79750. configurable: true
  79751. });
  79752. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  79753. /**
  79754. * Gets the current state of the task
  79755. */
  79756. get: function () {
  79757. return this._taskState;
  79758. },
  79759. enumerable: true,
  79760. configurable: true
  79761. });
  79762. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  79763. /**
  79764. * Gets the current error object (if task is in error)
  79765. */
  79766. get: function () {
  79767. return this._errorObject;
  79768. },
  79769. enumerable: true,
  79770. configurable: true
  79771. });
  79772. /**
  79773. * Internal only
  79774. * @ignore
  79775. */
  79776. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  79777. if (this._errorObject) {
  79778. return;
  79779. }
  79780. this._errorObject = {
  79781. message: message,
  79782. exception: exception
  79783. };
  79784. };
  79785. /**
  79786. * Execute the current task
  79787. * @param scene defines the scene where you want your assets to be loaded
  79788. * @param onSuccess is a callback called when the task is successfully executed
  79789. * @param onError is a callback called if an error occurs
  79790. */
  79791. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79792. var _this = this;
  79793. this._taskState = AssetTaskState.RUNNING;
  79794. this.runTask(scene, function () {
  79795. _this.onDoneCallback(onSuccess, onError);
  79796. }, function (msg, exception) {
  79797. _this.onErrorCallback(onError, msg, exception);
  79798. });
  79799. };
  79800. /**
  79801. * Execute the current task
  79802. * @param scene defines the scene where you want your assets to be loaded
  79803. * @param onSuccess is a callback called when the task is successfully executed
  79804. * @param onError is a callback called if an error occurs
  79805. */
  79806. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79807. throw new Error("runTask is not implemented");
  79808. };
  79809. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  79810. this._taskState = AssetTaskState.ERROR;
  79811. this._errorObject = {
  79812. message: message,
  79813. exception: exception
  79814. };
  79815. if (this.onError) {
  79816. this.onError(this, message, exception);
  79817. }
  79818. onError();
  79819. };
  79820. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  79821. try {
  79822. this._taskState = AssetTaskState.DONE;
  79823. this._isCompleted = true;
  79824. if (this.onSuccess) {
  79825. this.onSuccess(this);
  79826. }
  79827. onSuccess();
  79828. }
  79829. catch (e) {
  79830. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  79831. }
  79832. };
  79833. return AbstractAssetTask;
  79834. }());
  79835. BABYLON.AbstractAssetTask = AbstractAssetTask;
  79836. /**
  79837. * Class used to share progress information about assets loading
  79838. */
  79839. var AssetsProgressEvent = /** @class */ (function () {
  79840. /**
  79841. * Creates a {BABYLON.AssetsProgressEvent}
  79842. * @param remainingCount defines the number of remaining tasks to process
  79843. * @param totalCount defines the total number of tasks
  79844. * @param task defines the task that was just processed
  79845. */
  79846. function AssetsProgressEvent(remainingCount, totalCount, task) {
  79847. this.remainingCount = remainingCount;
  79848. this.totalCount = totalCount;
  79849. this.task = task;
  79850. }
  79851. return AssetsProgressEvent;
  79852. }());
  79853. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  79854. /**
  79855. * Define a task used by {BABYLON.AssetsManager} to load meshes
  79856. */
  79857. var MeshAssetTask = /** @class */ (function (_super) {
  79858. __extends(MeshAssetTask, _super);
  79859. /**
  79860. * Creates a new {BABYLON.MeshAssetTask}
  79861. * @param name defines the name of the task
  79862. * @param meshesNames defines the list of mesh's names you want to load
  79863. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  79864. * @param sceneFilename defines the filename of the scene to load from
  79865. */
  79866. function MeshAssetTask(
  79867. /**
  79868. * Defines the name of the task
  79869. */
  79870. name,
  79871. /**
  79872. * Defines the list of mesh's names you want to load
  79873. */
  79874. meshesNames,
  79875. /**
  79876. * Defines the root url to use as a base to load your meshes and associated resources
  79877. */
  79878. rootUrl,
  79879. /**
  79880. * Defines the filename of the scene to load from
  79881. */
  79882. sceneFilename) {
  79883. var _this = _super.call(this, name) || this;
  79884. _this.name = name;
  79885. _this.meshesNames = meshesNames;
  79886. _this.rootUrl = rootUrl;
  79887. _this.sceneFilename = sceneFilename;
  79888. return _this;
  79889. }
  79890. /**
  79891. * Execute the current task
  79892. * @param scene defines the scene where you want your assets to be loaded
  79893. * @param onSuccess is a callback called when the task is successfully executed
  79894. * @param onError is a callback called if an error occurs
  79895. */
  79896. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79897. var _this = this;
  79898. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  79899. _this.loadedMeshes = meshes;
  79900. _this.loadedParticleSystems = particleSystems;
  79901. _this.loadedSkeletons = skeletons;
  79902. onSuccess();
  79903. }, null, function (scene, message, exception) {
  79904. onError(message, exception);
  79905. });
  79906. };
  79907. return MeshAssetTask;
  79908. }(AbstractAssetTask));
  79909. BABYLON.MeshAssetTask = MeshAssetTask;
  79910. /**
  79911. * Define a task used by {BABYLON.AssetsManager} to load text content
  79912. */
  79913. var TextFileAssetTask = /** @class */ (function (_super) {
  79914. __extends(TextFileAssetTask, _super);
  79915. /**
  79916. * Creates a new TextFileAssetTask object
  79917. * @param name defines the name of the task
  79918. * @param url defines the location of the file to load
  79919. */
  79920. function TextFileAssetTask(
  79921. /**
  79922. * Defines the name of the task
  79923. */
  79924. name,
  79925. /**
  79926. * Defines the location of the file to load
  79927. */
  79928. url) {
  79929. var _this = _super.call(this, name) || this;
  79930. _this.name = name;
  79931. _this.url = url;
  79932. return _this;
  79933. }
  79934. /**
  79935. * Execute the current task
  79936. * @param scene defines the scene where you want your assets to be loaded
  79937. * @param onSuccess is a callback called when the task is successfully executed
  79938. * @param onError is a callback called if an error occurs
  79939. */
  79940. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79941. var _this = this;
  79942. scene._loadFile(this.url, function (data) {
  79943. _this.text = data;
  79944. onSuccess();
  79945. }, undefined, false, true, function (request, exception) {
  79946. if (request) {
  79947. onError(request.status + " " + request.statusText, exception);
  79948. }
  79949. });
  79950. };
  79951. return TextFileAssetTask;
  79952. }(AbstractAssetTask));
  79953. BABYLON.TextFileAssetTask = TextFileAssetTask;
  79954. /**
  79955. * Define a task used by {BABYLON.AssetsManager} to load binary data
  79956. */
  79957. var BinaryFileAssetTask = /** @class */ (function (_super) {
  79958. __extends(BinaryFileAssetTask, _super);
  79959. /**
  79960. * Creates a new BinaryFileAssetTask object
  79961. * @param name defines the name of the new task
  79962. * @param url defines the location of the file to load
  79963. */
  79964. function BinaryFileAssetTask(
  79965. /**
  79966. * Defines the name of the task
  79967. */
  79968. name,
  79969. /**
  79970. * Defines the location of the file to load
  79971. */
  79972. url) {
  79973. var _this = _super.call(this, name) || this;
  79974. _this.name = name;
  79975. _this.url = url;
  79976. return _this;
  79977. }
  79978. /**
  79979. * Execute the current task
  79980. * @param scene defines the scene where you want your assets to be loaded
  79981. * @param onSuccess is a callback called when the task is successfully executed
  79982. * @param onError is a callback called if an error occurs
  79983. */
  79984. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79985. var _this = this;
  79986. scene._loadFile(this.url, function (data) {
  79987. _this.data = data;
  79988. onSuccess();
  79989. }, undefined, true, true, function (request, exception) {
  79990. if (request) {
  79991. onError(request.status + " " + request.statusText, exception);
  79992. }
  79993. });
  79994. };
  79995. return BinaryFileAssetTask;
  79996. }(AbstractAssetTask));
  79997. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  79998. /**
  79999. * Define a task used by {BABYLON.AssetsManager} to load images
  80000. */
  80001. var ImageAssetTask = /** @class */ (function (_super) {
  80002. __extends(ImageAssetTask, _super);
  80003. /**
  80004. * Creates a new ImageAssetTask
  80005. * @param name defines the name of the task
  80006. * @param url defines the location of the image to load
  80007. */
  80008. function ImageAssetTask(
  80009. /**
  80010. * Defines the name of the task
  80011. */
  80012. name,
  80013. /**
  80014. * Defines the location of the image to load
  80015. */
  80016. url) {
  80017. var _this = _super.call(this, name) || this;
  80018. _this.name = name;
  80019. _this.url = url;
  80020. return _this;
  80021. }
  80022. /**
  80023. * Execute the current task
  80024. * @param scene defines the scene where you want your assets to be loaded
  80025. * @param onSuccess is a callback called when the task is successfully executed
  80026. * @param onError is a callback called if an error occurs
  80027. */
  80028. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80029. var _this = this;
  80030. var img = new Image();
  80031. BABYLON.Tools.SetCorsBehavior(this.url, img);
  80032. img.onload = function () {
  80033. _this.image = img;
  80034. onSuccess();
  80035. };
  80036. img.onerror = function (err) {
  80037. onError("Error loading image", err);
  80038. };
  80039. img.src = this.url;
  80040. };
  80041. return ImageAssetTask;
  80042. }(AbstractAssetTask));
  80043. BABYLON.ImageAssetTask = ImageAssetTask;
  80044. /**
  80045. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  80046. */
  80047. var TextureAssetTask = /** @class */ (function (_super) {
  80048. __extends(TextureAssetTask, _super);
  80049. /**
  80050. * Creates a new TextureAssetTask object
  80051. * @param name defines the name of the task
  80052. * @param url defines the location of the file to load
  80053. * @param noMipmap defines if mipmap should not be generated (default is false)
  80054. * @param invertY defines if texture must be inverted on Y axis (default is false)
  80055. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80056. */
  80057. function TextureAssetTask(
  80058. /**
  80059. * Defines the name of the task
  80060. */
  80061. name,
  80062. /**
  80063. * Defines the location of the file to load
  80064. */
  80065. url,
  80066. /**
  80067. * Defines if mipmap should not be generated (default is false)
  80068. */
  80069. noMipmap,
  80070. /**
  80071. * Defines if texture must be inverted on Y axis (default is false)
  80072. */
  80073. invertY,
  80074. /**
  80075. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80076. */
  80077. samplingMode) {
  80078. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80079. var _this = _super.call(this, name) || this;
  80080. _this.name = name;
  80081. _this.url = url;
  80082. _this.noMipmap = noMipmap;
  80083. _this.invertY = invertY;
  80084. _this.samplingMode = samplingMode;
  80085. return _this;
  80086. }
  80087. /**
  80088. * Execute the current task
  80089. * @param scene defines the scene where you want your assets to be loaded
  80090. * @param onSuccess is a callback called when the task is successfully executed
  80091. * @param onError is a callback called if an error occurs
  80092. */
  80093. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80094. var onload = function () {
  80095. onSuccess();
  80096. };
  80097. var onerror = function (message, exception) {
  80098. onError(message, exception);
  80099. };
  80100. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  80101. };
  80102. return TextureAssetTask;
  80103. }(AbstractAssetTask));
  80104. BABYLON.TextureAssetTask = TextureAssetTask;
  80105. /**
  80106. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  80107. */
  80108. var CubeTextureAssetTask = /** @class */ (function (_super) {
  80109. __extends(CubeTextureAssetTask, _super);
  80110. /**
  80111. * Creates a new CubeTextureAssetTask
  80112. * @param name defines the name of the task
  80113. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80114. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80115. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80116. * @param files defines the explicit list of files (undefined by default)
  80117. */
  80118. function CubeTextureAssetTask(
  80119. /**
  80120. * Defines the name of the task
  80121. */
  80122. name,
  80123. /**
  80124. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80125. */
  80126. url,
  80127. /**
  80128. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80129. */
  80130. extensions,
  80131. /**
  80132. * Defines if mipmaps should not be generated (default is false)
  80133. */
  80134. noMipmap,
  80135. /**
  80136. * Defines the explicit list of files (undefined by default)
  80137. */
  80138. files) {
  80139. var _this = _super.call(this, name) || this;
  80140. _this.name = name;
  80141. _this.url = url;
  80142. _this.extensions = extensions;
  80143. _this.noMipmap = noMipmap;
  80144. _this.files = files;
  80145. return _this;
  80146. }
  80147. /**
  80148. * Execute the current task
  80149. * @param scene defines the scene where you want your assets to be loaded
  80150. * @param onSuccess is a callback called when the task is successfully executed
  80151. * @param onError is a callback called if an error occurs
  80152. */
  80153. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80154. var onload = function () {
  80155. onSuccess();
  80156. };
  80157. var onerror = function (message, exception) {
  80158. onError(message, exception);
  80159. };
  80160. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  80161. };
  80162. return CubeTextureAssetTask;
  80163. }(AbstractAssetTask));
  80164. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  80165. /**
  80166. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  80167. */
  80168. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  80169. __extends(HDRCubeTextureAssetTask, _super);
  80170. /**
  80171. * Creates a new HDRCubeTextureAssetTask object
  80172. * @param name defines the name of the task
  80173. * @param url defines the location of the file to load
  80174. * @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.
  80175. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80176. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80177. * @param useInGammaSpace 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)
  80178. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80179. */
  80180. function HDRCubeTextureAssetTask(
  80181. /**
  80182. * Defines the name of the task
  80183. */
  80184. name,
  80185. /**
  80186. * Defines the location of the file to load
  80187. */
  80188. url,
  80189. /**
  80190. * 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.
  80191. */
  80192. size,
  80193. /**
  80194. * Defines if mipmaps should not be generated (default is false)
  80195. */
  80196. noMipmap,
  80197. /**
  80198. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80199. */
  80200. generateHarmonics,
  80201. /**
  80202. * 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)
  80203. */
  80204. useInGammaSpace,
  80205. /**
  80206. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80207. */
  80208. usePMREMGenerator) {
  80209. if (noMipmap === void 0) { noMipmap = false; }
  80210. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80211. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80212. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80213. var _this = _super.call(this, name) || this;
  80214. _this.name = name;
  80215. _this.url = url;
  80216. _this.size = size;
  80217. _this.noMipmap = noMipmap;
  80218. _this.generateHarmonics = generateHarmonics;
  80219. _this.useInGammaSpace = useInGammaSpace;
  80220. _this.usePMREMGenerator = usePMREMGenerator;
  80221. return _this;
  80222. }
  80223. /**
  80224. * Execute the current task
  80225. * @param scene defines the scene where you want your assets to be loaded
  80226. * @param onSuccess is a callback called when the task is successfully executed
  80227. * @param onError is a callback called if an error occurs
  80228. */
  80229. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80230. var onload = function () {
  80231. onSuccess();
  80232. };
  80233. var onerror = function (message, exception) {
  80234. onError(message, exception);
  80235. };
  80236. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  80237. };
  80238. return HDRCubeTextureAssetTask;
  80239. }(AbstractAssetTask));
  80240. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  80241. /**
  80242. * This class can be used to easily import assets into a scene
  80243. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  80244. */
  80245. var AssetsManager = /** @class */ (function () {
  80246. /**
  80247. * Creates a new AssetsManager
  80248. * @param scene defines the scene to work on
  80249. */
  80250. function AssetsManager(scene) {
  80251. this._isLoading = false;
  80252. this._tasks = new Array();
  80253. this._waitingTasksCount = 0;
  80254. this._totalTasksCount = 0;
  80255. /**
  80256. * Observable called when all tasks are processed
  80257. */
  80258. this.onTaskSuccessObservable = new BABYLON.Observable();
  80259. /**
  80260. * Observable called when a task had an error
  80261. */
  80262. this.onTaskErrorObservable = new BABYLON.Observable();
  80263. /**
  80264. * Observable called when a task is successful
  80265. */
  80266. this.onTasksDoneObservable = new BABYLON.Observable();
  80267. /**
  80268. * Observable called when a task is done (whatever the result is)
  80269. */
  80270. this.onProgressObservable = new BABYLON.Observable();
  80271. /**
  80272. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  80273. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  80274. */
  80275. this.useDefaultLoadingScreen = true;
  80276. this._scene = scene;
  80277. }
  80278. /**
  80279. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  80280. * @param taskName defines the name of the new task
  80281. * @param meshesNames defines the name of meshes to load
  80282. * @param rootUrl defines the root url to use to locate files
  80283. * @param sceneFilename defines the filename of the scene file
  80284. * @returns a new {BABYLON.MeshAssetTask} object
  80285. */
  80286. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  80287. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  80288. this._tasks.push(task);
  80289. return task;
  80290. };
  80291. /**
  80292. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  80293. * @param taskName defines the name of the new task
  80294. * @param url defines the url of the file to load
  80295. * @returns a new {BABYLON.TextFileAssetTask} object
  80296. */
  80297. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  80298. var task = new TextFileAssetTask(taskName, url);
  80299. this._tasks.push(task);
  80300. return task;
  80301. };
  80302. /**
  80303. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  80304. * @param taskName defines the name of the new task
  80305. * @param url defines the url of the file to load
  80306. * @returns a new {BABYLON.BinaryFileAssetTask} object
  80307. */
  80308. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  80309. var task = new BinaryFileAssetTask(taskName, url);
  80310. this._tasks.push(task);
  80311. return task;
  80312. };
  80313. /**
  80314. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  80315. * @param taskName defines the name of the new task
  80316. * @param url defines the url of the file to load
  80317. * @returns a new {BABYLON.ImageAssetTask} object
  80318. */
  80319. AssetsManager.prototype.addImageTask = function (taskName, url) {
  80320. var task = new ImageAssetTask(taskName, url);
  80321. this._tasks.push(task);
  80322. return task;
  80323. };
  80324. /**
  80325. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  80326. * @param taskName defines the name of the new task
  80327. * @param url defines the url of the file to load
  80328. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80329. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  80330. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  80331. * @returns a new {BABYLON.TextureAssetTask} object
  80332. */
  80333. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  80334. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80335. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  80336. this._tasks.push(task);
  80337. return task;
  80338. };
  80339. /**
  80340. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  80341. * @param taskName defines the name of the new task
  80342. * @param url defines the url of the file to load
  80343. * @param extensions defines the extension to use to load the cube map (can be null)
  80344. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80345. * @param files defines the list of files to load (can be null)
  80346. * @returns a new {BABYLON.CubeTextureAssetTask} object
  80347. */
  80348. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  80349. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  80350. this._tasks.push(task);
  80351. return task;
  80352. };
  80353. /**
  80354. *
  80355. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  80356. * @param taskName defines the name of the new task
  80357. * @param url defines the url of the file to load
  80358. * @param size defines the size you want for the cubemap (can be null)
  80359. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80360. * @param generateHarmonics defines if you want to automatically generate (true by default)
  80361. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  80362. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  80363. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  80364. */
  80365. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  80366. if (noMipmap === void 0) { noMipmap = false; }
  80367. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80368. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80369. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80370. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  80371. this._tasks.push(task);
  80372. return task;
  80373. };
  80374. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  80375. var _this = this;
  80376. this._waitingTasksCount--;
  80377. try {
  80378. if (task.taskState === AssetTaskState.DONE) {
  80379. // Let's remove successfull tasks
  80380. BABYLON.Tools.SetImmediate(function () {
  80381. var index = _this._tasks.indexOf(task);
  80382. if (index > -1) {
  80383. _this._tasks.splice(index, 1);
  80384. }
  80385. });
  80386. }
  80387. if (this.onProgress) {
  80388. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  80389. }
  80390. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  80391. }
  80392. catch (e) {
  80393. BABYLON.Tools.Error("Error running progress callbacks.");
  80394. console.log(e);
  80395. }
  80396. if (this._waitingTasksCount === 0) {
  80397. try {
  80398. if (this.onFinish) {
  80399. this.onFinish(this._tasks);
  80400. }
  80401. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80402. }
  80403. catch (e) {
  80404. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  80405. console.log(e);
  80406. }
  80407. this._isLoading = false;
  80408. this._scene.getEngine().hideLoadingUI();
  80409. }
  80410. };
  80411. AssetsManager.prototype._runTask = function (task) {
  80412. var _this = this;
  80413. var done = function () {
  80414. try {
  80415. if (_this.onTaskSuccess) {
  80416. _this.onTaskSuccess(task);
  80417. }
  80418. _this.onTaskSuccessObservable.notifyObservers(task);
  80419. _this._decreaseWaitingTasksCount(task);
  80420. }
  80421. catch (e) {
  80422. error("Error executing task success callbacks", e);
  80423. }
  80424. };
  80425. var error = function (message, exception) {
  80426. task._setErrorObject(message, exception);
  80427. if (_this.onTaskError) {
  80428. _this.onTaskError(task);
  80429. }
  80430. _this.onTaskErrorObservable.notifyObservers(task);
  80431. _this._decreaseWaitingTasksCount(task);
  80432. };
  80433. task.run(this._scene, done, error);
  80434. };
  80435. /**
  80436. * Reset the {BABYLON.AssetsManager} and remove all tasks
  80437. * @return the current instance of the {BABYLON.AssetsManager}
  80438. */
  80439. AssetsManager.prototype.reset = function () {
  80440. this._isLoading = false;
  80441. this._tasks = new Array();
  80442. return this;
  80443. };
  80444. /**
  80445. * Start the loading process
  80446. * @return the current instance of the {BABYLON.AssetsManager}
  80447. */
  80448. AssetsManager.prototype.load = function () {
  80449. if (this._isLoading) {
  80450. return this;
  80451. }
  80452. this._isLoading = true;
  80453. this._waitingTasksCount = this._tasks.length;
  80454. this._totalTasksCount = this._tasks.length;
  80455. if (this._waitingTasksCount === 0) {
  80456. if (this.onFinish) {
  80457. this.onFinish(this._tasks);
  80458. }
  80459. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80460. return this;
  80461. }
  80462. if (this.useDefaultLoadingScreen) {
  80463. this._scene.getEngine().displayLoadingUI();
  80464. }
  80465. for (var index = 0; index < this._tasks.length; index++) {
  80466. var task = this._tasks[index];
  80467. this._runTask(task);
  80468. }
  80469. return this;
  80470. };
  80471. return AssetsManager;
  80472. }());
  80473. BABYLON.AssetsManager = AssetsManager;
  80474. })(BABYLON || (BABYLON = {}));
  80475. //# sourceMappingURL=babylon.assetsManager.js.map
  80476. var BABYLON;
  80477. (function (BABYLON) {
  80478. var serializedGeometries = [];
  80479. var serializeGeometry = function (geometry, serializationGeometries) {
  80480. if (serializedGeometries[geometry.id]) {
  80481. return;
  80482. }
  80483. if (geometry.doNotSerialize) {
  80484. return;
  80485. }
  80486. if (geometry instanceof BABYLON.BoxGeometry) {
  80487. serializationGeometries.boxes.push(geometry.serialize());
  80488. }
  80489. else if (geometry instanceof BABYLON.SphereGeometry) {
  80490. serializationGeometries.spheres.push(geometry.serialize());
  80491. }
  80492. else if (geometry instanceof BABYLON.CylinderGeometry) {
  80493. serializationGeometries.cylinders.push(geometry.serialize());
  80494. }
  80495. else if (geometry instanceof BABYLON.TorusGeometry) {
  80496. serializationGeometries.toruses.push(geometry.serialize());
  80497. }
  80498. else if (geometry instanceof BABYLON.GroundGeometry) {
  80499. serializationGeometries.grounds.push(geometry.serialize());
  80500. }
  80501. else if (geometry instanceof BABYLON.Plane) {
  80502. serializationGeometries.planes.push(geometry.serialize());
  80503. }
  80504. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  80505. serializationGeometries.torusKnots.push(geometry.serialize());
  80506. }
  80507. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  80508. throw new Error("Unknown primitive type");
  80509. }
  80510. else {
  80511. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  80512. }
  80513. serializedGeometries[geometry.id] = true;
  80514. };
  80515. var serializeMesh = function (mesh, serializationScene) {
  80516. var serializationObject = {};
  80517. // Geometry
  80518. var geometry = mesh._geometry;
  80519. if (geometry) {
  80520. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  80521. // 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
  80522. serializeGeometry(geometry, serializationScene.geometries);
  80523. }
  80524. }
  80525. // Custom
  80526. if (mesh.serialize) {
  80527. mesh.serialize(serializationObject);
  80528. }
  80529. return serializationObject;
  80530. };
  80531. var finalizeSingleMesh = function (mesh, serializationObject) {
  80532. //only works if the mesh is already loaded
  80533. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80534. //serialize material
  80535. if (mesh.material) {
  80536. if (mesh.material instanceof BABYLON.StandardMaterial) {
  80537. serializationObject.materials = serializationObject.materials || [];
  80538. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80539. serializationObject.materials.push(mesh.material.serialize());
  80540. }
  80541. }
  80542. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  80543. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  80544. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80545. serializationObject.multiMaterials.push(mesh.material.serialize());
  80546. }
  80547. }
  80548. }
  80549. //serialize geometry
  80550. var geometry = mesh._geometry;
  80551. if (geometry) {
  80552. if (!serializationObject.geometries) {
  80553. serializationObject.geometries = {};
  80554. serializationObject.geometries.boxes = [];
  80555. serializationObject.geometries.spheres = [];
  80556. serializationObject.geometries.cylinders = [];
  80557. serializationObject.geometries.toruses = [];
  80558. serializationObject.geometries.grounds = [];
  80559. serializationObject.geometries.planes = [];
  80560. serializationObject.geometries.torusKnots = [];
  80561. serializationObject.geometries.vertexData = [];
  80562. }
  80563. serializeGeometry(geometry, serializationObject.geometries);
  80564. }
  80565. // Skeletons
  80566. if (mesh.skeleton) {
  80567. serializationObject.skeletons = serializationObject.skeletons || [];
  80568. serializationObject.skeletons.push(mesh.skeleton.serialize());
  80569. }
  80570. //serialize the actual mesh
  80571. serializationObject.meshes = serializationObject.meshes || [];
  80572. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80573. }
  80574. };
  80575. var SceneSerializer = /** @class */ (function () {
  80576. function SceneSerializer() {
  80577. }
  80578. SceneSerializer.ClearCache = function () {
  80579. serializedGeometries = [];
  80580. };
  80581. SceneSerializer.Serialize = function (scene) {
  80582. var serializationObject = {};
  80583. SceneSerializer.ClearCache();
  80584. // Scene
  80585. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  80586. serializationObject.autoClear = scene.autoClear;
  80587. serializationObject.clearColor = scene.clearColor.asArray();
  80588. serializationObject.ambientColor = scene.ambientColor.asArray();
  80589. serializationObject.gravity = scene.gravity.asArray();
  80590. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  80591. serializationObject.workerCollisions = scene.workerCollisions;
  80592. // Fog
  80593. if (scene.fogMode && scene.fogMode !== 0) {
  80594. serializationObject.fogMode = scene.fogMode;
  80595. serializationObject.fogColor = scene.fogColor.asArray();
  80596. serializationObject.fogStart = scene.fogStart;
  80597. serializationObject.fogEnd = scene.fogEnd;
  80598. serializationObject.fogDensity = scene.fogDensity;
  80599. }
  80600. //Physics
  80601. if (scene.isPhysicsEnabled()) {
  80602. var physicEngine = scene.getPhysicsEngine();
  80603. if (physicEngine) {
  80604. serializationObject.physicsEnabled = true;
  80605. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  80606. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  80607. }
  80608. }
  80609. // Metadata
  80610. if (scene.metadata) {
  80611. serializationObject.metadata = scene.metadata;
  80612. }
  80613. // Morph targets
  80614. serializationObject.morphTargetManagers = [];
  80615. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80616. var abstractMesh = _a[_i];
  80617. var manager = abstractMesh.morphTargetManager;
  80618. if (manager) {
  80619. serializationObject.morphTargetManagers.push(manager.serialize());
  80620. }
  80621. }
  80622. // Lights
  80623. serializationObject.lights = [];
  80624. var index;
  80625. var light;
  80626. for (index = 0; index < scene.lights.length; index++) {
  80627. light = scene.lights[index];
  80628. if (!light.doNotSerialize) {
  80629. serializationObject.lights.push(light.serialize());
  80630. }
  80631. }
  80632. // Cameras
  80633. serializationObject.cameras = [];
  80634. for (index = 0; index < scene.cameras.length; index++) {
  80635. var camera = scene.cameras[index];
  80636. if (!camera.doNotSerialize) {
  80637. serializationObject.cameras.push(camera.serialize());
  80638. }
  80639. }
  80640. if (scene.activeCamera) {
  80641. serializationObject.activeCameraID = scene.activeCamera.id;
  80642. }
  80643. // Animations
  80644. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80645. // Materials
  80646. serializationObject.materials = [];
  80647. serializationObject.multiMaterials = [];
  80648. var material;
  80649. for (index = 0; index < scene.materials.length; index++) {
  80650. material = scene.materials[index];
  80651. if (!material.doNotSerialize) {
  80652. serializationObject.materials.push(material.serialize());
  80653. }
  80654. }
  80655. // MultiMaterials
  80656. serializationObject.multiMaterials = [];
  80657. for (index = 0; index < scene.multiMaterials.length; index++) {
  80658. var multiMaterial = scene.multiMaterials[index];
  80659. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80660. }
  80661. // Environment texture
  80662. if (scene.environmentTexture) {
  80663. serializationObject.environmentTexture = scene.environmentTexture.name;
  80664. }
  80665. // Skeletons
  80666. serializationObject.skeletons = [];
  80667. for (index = 0; index < scene.skeletons.length; index++) {
  80668. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  80669. }
  80670. // Transform nodes
  80671. serializationObject.transformNodes = [];
  80672. for (index = 0; index < scene.transformNodes.length; index++) {
  80673. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  80674. }
  80675. // Geometries
  80676. serializationObject.geometries = {};
  80677. serializationObject.geometries.boxes = [];
  80678. serializationObject.geometries.spheres = [];
  80679. serializationObject.geometries.cylinders = [];
  80680. serializationObject.geometries.toruses = [];
  80681. serializationObject.geometries.grounds = [];
  80682. serializationObject.geometries.planes = [];
  80683. serializationObject.geometries.torusKnots = [];
  80684. serializationObject.geometries.vertexData = [];
  80685. serializedGeometries = [];
  80686. var geometries = scene.getGeometries();
  80687. for (index = 0; index < geometries.length; index++) {
  80688. var geometry = geometries[index];
  80689. if (geometry.isReady()) {
  80690. serializeGeometry(geometry, serializationObject.geometries);
  80691. }
  80692. }
  80693. // Meshes
  80694. serializationObject.meshes = [];
  80695. for (index = 0; index < scene.meshes.length; index++) {
  80696. var abstractMesh = scene.meshes[index];
  80697. if (abstractMesh instanceof BABYLON.Mesh) {
  80698. var mesh = abstractMesh;
  80699. if (!mesh.doNotSerialize) {
  80700. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80701. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80702. }
  80703. }
  80704. }
  80705. }
  80706. // Particles Systems
  80707. serializationObject.particleSystems = [];
  80708. for (index = 0; index < scene.particleSystems.length; index++) {
  80709. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  80710. }
  80711. // Lens flares
  80712. serializationObject.lensFlareSystems = [];
  80713. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  80714. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  80715. }
  80716. // Shadows
  80717. serializationObject.shadowGenerators = [];
  80718. for (index = 0; index < scene.lights.length; index++) {
  80719. light = scene.lights[index];
  80720. var shadowGenerator = light.getShadowGenerator();
  80721. if (shadowGenerator) {
  80722. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  80723. }
  80724. }
  80725. // Action Manager
  80726. if (scene.actionManager) {
  80727. serializationObject.actions = scene.actionManager.serialize("scene");
  80728. }
  80729. // Audio
  80730. serializationObject.sounds = [];
  80731. for (index = 0; index < scene.soundTracks.length; index++) {
  80732. var soundtrack = scene.soundTracks[index];
  80733. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  80734. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  80735. }
  80736. }
  80737. return serializationObject;
  80738. };
  80739. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  80740. if (withParents === void 0) { withParents = false; }
  80741. if (withChildren === void 0) { withChildren = false; }
  80742. var serializationObject = {};
  80743. SceneSerializer.ClearCache();
  80744. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  80745. if (withParents || withChildren) {
  80746. //deliberate for loop! not for each, appended should be processed as well.
  80747. for (var i = 0; i < toSerialize.length; ++i) {
  80748. if (withChildren) {
  80749. toSerialize[i].getDescendants().forEach(function (node) {
  80750. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  80751. toSerialize.push(node);
  80752. }
  80753. });
  80754. }
  80755. //make sure the array doesn't contain the object already
  80756. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  80757. toSerialize.push(toSerialize[i].parent);
  80758. }
  80759. }
  80760. }
  80761. toSerialize.forEach(function (mesh) {
  80762. finalizeSingleMesh(mesh, serializationObject);
  80763. });
  80764. return serializationObject;
  80765. };
  80766. return SceneSerializer;
  80767. }());
  80768. BABYLON.SceneSerializer = SceneSerializer;
  80769. })(BABYLON || (BABYLON = {}));
  80770. //# sourceMappingURL=babylon.sceneSerializer.js.map
  80771. var BABYLON;
  80772. (function (BABYLON) {
  80773. var ReflectionProbe = /** @class */ (function () {
  80774. function ReflectionProbe(name, size, scene, generateMipMaps) {
  80775. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80776. var _this = this;
  80777. this.name = name;
  80778. this._viewMatrix = BABYLON.Matrix.Identity();
  80779. this._target = BABYLON.Vector3.Zero();
  80780. this._add = BABYLON.Vector3.Zero();
  80781. this.invertYAxis = false;
  80782. this.position = BABYLON.Vector3.Zero();
  80783. this._scene = scene;
  80784. this._scene.reflectionProbes.push(this);
  80785. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  80786. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  80787. switch (faceIndex) {
  80788. case 0:
  80789. _this._add.copyFromFloats(1, 0, 0);
  80790. break;
  80791. case 1:
  80792. _this._add.copyFromFloats(-1, 0, 0);
  80793. break;
  80794. case 2:
  80795. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  80796. break;
  80797. case 3:
  80798. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  80799. break;
  80800. case 4:
  80801. _this._add.copyFromFloats(0, 0, 1);
  80802. break;
  80803. case 5:
  80804. _this._add.copyFromFloats(0, 0, -1);
  80805. break;
  80806. }
  80807. if (_this._attachedMesh) {
  80808. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  80809. }
  80810. _this.position.addToRef(_this._add, _this._target);
  80811. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  80812. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  80813. scene._forcedViewPosition = _this.position;
  80814. });
  80815. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  80816. scene._forcedViewPosition = null;
  80817. scene.updateTransformMatrix(true);
  80818. });
  80819. if (scene.activeCamera) {
  80820. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80821. }
  80822. }
  80823. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  80824. get: function () {
  80825. return this._renderTargetTexture.samples;
  80826. },
  80827. set: function (value) {
  80828. this._renderTargetTexture.samples = value;
  80829. },
  80830. enumerable: true,
  80831. configurable: true
  80832. });
  80833. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  80834. get: function () {
  80835. return this._renderTargetTexture.refreshRate;
  80836. },
  80837. set: function (value) {
  80838. this._renderTargetTexture.refreshRate = value;
  80839. },
  80840. enumerable: true,
  80841. configurable: true
  80842. });
  80843. ReflectionProbe.prototype.getScene = function () {
  80844. return this._scene;
  80845. };
  80846. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  80847. get: function () {
  80848. return this._renderTargetTexture;
  80849. },
  80850. enumerable: true,
  80851. configurable: true
  80852. });
  80853. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  80854. get: function () {
  80855. return this._renderTargetTexture.renderList;
  80856. },
  80857. enumerable: true,
  80858. configurable: true
  80859. });
  80860. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  80861. this._attachedMesh = mesh;
  80862. };
  80863. /**
  80864. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  80865. *
  80866. * @param renderingGroupId The rendering group id corresponding to its index
  80867. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  80868. */
  80869. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  80870. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  80871. };
  80872. ReflectionProbe.prototype.dispose = function () {
  80873. var index = this._scene.reflectionProbes.indexOf(this);
  80874. if (index !== -1) {
  80875. // Remove from the scene if found
  80876. this._scene.reflectionProbes.splice(index, 1);
  80877. }
  80878. if (this._renderTargetTexture) {
  80879. this._renderTargetTexture.dispose();
  80880. this._renderTargetTexture = null;
  80881. }
  80882. };
  80883. return ReflectionProbe;
  80884. }());
  80885. BABYLON.ReflectionProbe = ReflectionProbe;
  80886. })(BABYLON || (BABYLON = {}));
  80887. //# sourceMappingURL=babylon.reflectionProbe.js.map
  80888. var BABYLON;
  80889. (function (BABYLON) {
  80890. var Layer = /** @class */ (function () {
  80891. function Layer(name, imgUrl, scene, isBackground, color) {
  80892. this.name = name;
  80893. this.scale = new BABYLON.Vector2(1, 1);
  80894. this.offset = new BABYLON.Vector2(0, 0);
  80895. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  80896. this.layerMask = 0x0FFFFFFF;
  80897. this._vertexBuffers = {};
  80898. // Events
  80899. /**
  80900. * An event triggered when the layer is disposed.
  80901. * @type {BABYLON.Observable}
  80902. */
  80903. this.onDisposeObservable = new BABYLON.Observable();
  80904. /**
  80905. * An event triggered before rendering the scene
  80906. * @type {BABYLON.Observable}
  80907. */
  80908. this.onBeforeRenderObservable = new BABYLON.Observable();
  80909. /**
  80910. * An event triggered after rendering the scene
  80911. * @type {BABYLON.Observable}
  80912. */
  80913. this.onAfterRenderObservable = new BABYLON.Observable();
  80914. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  80915. this.isBackground = isBackground === undefined ? true : isBackground;
  80916. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  80917. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  80918. this._scene.layers.push(this);
  80919. var engine = this._scene.getEngine();
  80920. // VBO
  80921. var vertices = [];
  80922. vertices.push(1, 1);
  80923. vertices.push(-1, 1);
  80924. vertices.push(-1, -1);
  80925. vertices.push(1, -1);
  80926. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80927. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  80928. this._createIndexBuffer();
  80929. // Effects
  80930. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  80931. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  80932. }
  80933. Object.defineProperty(Layer.prototype, "onDispose", {
  80934. set: function (callback) {
  80935. if (this._onDisposeObserver) {
  80936. this.onDisposeObservable.remove(this._onDisposeObserver);
  80937. }
  80938. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  80939. },
  80940. enumerable: true,
  80941. configurable: true
  80942. });
  80943. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  80944. set: function (callback) {
  80945. if (this._onBeforeRenderObserver) {
  80946. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  80947. }
  80948. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  80949. },
  80950. enumerable: true,
  80951. configurable: true
  80952. });
  80953. Object.defineProperty(Layer.prototype, "onAfterRender", {
  80954. set: function (callback) {
  80955. if (this._onAfterRenderObserver) {
  80956. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80957. }
  80958. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  80959. },
  80960. enumerable: true,
  80961. configurable: true
  80962. });
  80963. Layer.prototype._createIndexBuffer = function () {
  80964. var engine = this._scene.getEngine();
  80965. // Indices
  80966. var indices = [];
  80967. indices.push(0);
  80968. indices.push(1);
  80969. indices.push(2);
  80970. indices.push(0);
  80971. indices.push(2);
  80972. indices.push(3);
  80973. this._indexBuffer = engine.createIndexBuffer(indices);
  80974. };
  80975. Layer.prototype._rebuild = function () {
  80976. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80977. if (vb) {
  80978. vb._rebuild();
  80979. }
  80980. this._createIndexBuffer();
  80981. };
  80982. Layer.prototype.render = function () {
  80983. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  80984. // Check
  80985. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  80986. return;
  80987. var engine = this._scene.getEngine();
  80988. this.onBeforeRenderObservable.notifyObservers(this);
  80989. // Render
  80990. engine.enableEffect(currentEffect);
  80991. engine.setState(false);
  80992. // Texture
  80993. currentEffect.setTexture("textureSampler", this.texture);
  80994. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  80995. // Color
  80996. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  80997. // Scale / offset
  80998. currentEffect.setVector2("offset", this.offset);
  80999. currentEffect.setVector2("scale", this.scale);
  81000. // VBOs
  81001. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81002. // Draw order
  81003. if (!this.alphaTest) {
  81004. engine.setAlphaMode(this.alphaBlendingMode);
  81005. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81007. }
  81008. else {
  81009. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81010. }
  81011. this.onAfterRenderObservable.notifyObservers(this);
  81012. };
  81013. Layer.prototype.dispose = function () {
  81014. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81015. if (vertexBuffer) {
  81016. vertexBuffer.dispose();
  81017. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81018. }
  81019. if (this._indexBuffer) {
  81020. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81021. this._indexBuffer = null;
  81022. }
  81023. if (this.texture) {
  81024. this.texture.dispose();
  81025. this.texture = null;
  81026. }
  81027. // Remove from scene
  81028. var index = this._scene.layers.indexOf(this);
  81029. this._scene.layers.splice(index, 1);
  81030. // Callback
  81031. this.onDisposeObservable.notifyObservers(this);
  81032. this.onDisposeObservable.clear();
  81033. this.onAfterRenderObservable.clear();
  81034. this.onBeforeRenderObservable.clear();
  81035. };
  81036. return Layer;
  81037. }());
  81038. BABYLON.Layer = Layer;
  81039. })(BABYLON || (BABYLON = {}));
  81040. //# sourceMappingURL=babylon.layer.js.map
  81041. var BABYLON;
  81042. (function (BABYLON) {
  81043. var TextureTools = /** @class */ (function () {
  81044. function TextureTools() {
  81045. }
  81046. /**
  81047. * Uses the GPU to create a copy texture rescaled at a given size
  81048. * @param texture Texture to copy from
  81049. * @param width Desired width
  81050. * @param height Desired height
  81051. * @return Generated texture
  81052. */
  81053. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  81054. if (useBilinearMode === void 0) { useBilinearMode = true; }
  81055. var scene = texture.getScene();
  81056. var engine = scene.getEngine();
  81057. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  81058. rtt.wrapU = texture.wrapU;
  81059. rtt.wrapV = texture.wrapV;
  81060. rtt.uOffset = texture.uOffset;
  81061. rtt.vOffset = texture.vOffset;
  81062. rtt.uScale = texture.uScale;
  81063. rtt.vScale = texture.vScale;
  81064. rtt.uAng = texture.uAng;
  81065. rtt.vAng = texture.vAng;
  81066. rtt.wAng = texture.wAng;
  81067. rtt.coordinatesIndex = texture.coordinatesIndex;
  81068. rtt.level = texture.level;
  81069. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  81070. rtt._texture.isReady = false;
  81071. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81072. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81073. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81074. passPostProcess.getEffect().executeWhenCompiled(function () {
  81075. passPostProcess.onApply = function (effect) {
  81076. effect.setTexture("textureSampler", texture);
  81077. };
  81078. var internalTexture = rtt.getInternalTexture();
  81079. if (internalTexture) {
  81080. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  81081. engine.unBindFramebuffer(internalTexture);
  81082. rtt.disposeFramebufferObjects();
  81083. passPostProcess.dispose();
  81084. internalTexture.isReady = true;
  81085. }
  81086. });
  81087. return rtt;
  81088. };
  81089. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  81090. if (!scene._environmentBRDFTexture) {
  81091. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81092. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81093. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81094. scene._environmentBRDFTexture = texture;
  81095. }
  81096. return scene._environmentBRDFTexture;
  81097. };
  81098. 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=";
  81099. return TextureTools;
  81100. }());
  81101. BABYLON.TextureTools = TextureTools;
  81102. })(BABYLON || (BABYLON = {}));
  81103. //# sourceMappingURL=babylon.textureTools.js.map
  81104. var BABYLON;
  81105. (function (BABYLON) {
  81106. var FramingBehavior = /** @class */ (function () {
  81107. function FramingBehavior() {
  81108. this._mode = FramingBehavior.FitFrustumSidesMode;
  81109. this._radiusScale = 1.0;
  81110. this._positionScale = 0.5;
  81111. this._defaultElevation = 0.3;
  81112. this._elevationReturnTime = 1500;
  81113. this._elevationReturnWaitTime = 1000;
  81114. this._zoomStopsAnimation = false;
  81115. this._framingTime = 1500;
  81116. this._isPointerDown = false;
  81117. this._lastInteractionTime = -Infinity;
  81118. // Framing control
  81119. this._animatables = new Array();
  81120. this._betaIsAnimating = false;
  81121. }
  81122. Object.defineProperty(FramingBehavior.prototype, "name", {
  81123. get: function () {
  81124. return "Framing";
  81125. },
  81126. enumerable: true,
  81127. configurable: true
  81128. });
  81129. Object.defineProperty(FramingBehavior.prototype, "mode", {
  81130. /**
  81131. * Gets current mode used by the behavior.
  81132. */
  81133. get: function () {
  81134. return this._mode;
  81135. },
  81136. /**
  81137. * Sets the current mode used by the behavior
  81138. */
  81139. set: function (mode) {
  81140. this._mode = mode;
  81141. },
  81142. enumerable: true,
  81143. configurable: true
  81144. });
  81145. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  81146. /**
  81147. * Gets the scale applied to the radius
  81148. */
  81149. get: function () {
  81150. return this._radiusScale;
  81151. },
  81152. /**
  81153. * Sets the scale applied to the radius (1 by default)
  81154. */
  81155. set: function (radius) {
  81156. this._radiusScale = radius;
  81157. },
  81158. enumerable: true,
  81159. configurable: true
  81160. });
  81161. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  81162. /**
  81163. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81164. */
  81165. get: function () {
  81166. return this._positionScale;
  81167. },
  81168. /**
  81169. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81170. */
  81171. set: function (scale) {
  81172. this._positionScale = scale;
  81173. },
  81174. enumerable: true,
  81175. configurable: true
  81176. });
  81177. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  81178. /**
  81179. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81180. * behaviour is triggered, in radians.
  81181. */
  81182. get: function () {
  81183. return this._defaultElevation;
  81184. },
  81185. /**
  81186. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81187. * behaviour is triggered, in radians.
  81188. */
  81189. set: function (elevation) {
  81190. this._defaultElevation = elevation;
  81191. },
  81192. enumerable: true,
  81193. configurable: true
  81194. });
  81195. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  81196. /**
  81197. * Gets the time (in milliseconds) taken to return to the default beta position.
  81198. * Negative value indicates camera should not return to default.
  81199. */
  81200. get: function () {
  81201. return this._elevationReturnTime;
  81202. },
  81203. /**
  81204. * Sets the time (in milliseconds) taken to return to the default beta position.
  81205. * Negative value indicates camera should not return to default.
  81206. */
  81207. set: function (speed) {
  81208. this._elevationReturnTime = speed;
  81209. },
  81210. enumerable: true,
  81211. configurable: true
  81212. });
  81213. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  81214. /**
  81215. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81216. */
  81217. get: function () {
  81218. return this._elevationReturnWaitTime;
  81219. },
  81220. /**
  81221. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81222. */
  81223. set: function (time) {
  81224. this._elevationReturnWaitTime = time;
  81225. },
  81226. enumerable: true,
  81227. configurable: true
  81228. });
  81229. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  81230. /**
  81231. * Gets the flag that indicates if user zooming should stop animation.
  81232. */
  81233. get: function () {
  81234. return this._zoomStopsAnimation;
  81235. },
  81236. /**
  81237. * Sets the flag that indicates if user zooming should stop animation.
  81238. */
  81239. set: function (flag) {
  81240. this._zoomStopsAnimation = flag;
  81241. },
  81242. enumerable: true,
  81243. configurable: true
  81244. });
  81245. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  81246. /**
  81247. * Gets the transition time when framing the mesh, in milliseconds
  81248. */
  81249. get: function () {
  81250. return this._framingTime;
  81251. },
  81252. /**
  81253. * Sets the transition time when framing the mesh, in milliseconds
  81254. */
  81255. set: function (time) {
  81256. this._framingTime = time;
  81257. },
  81258. enumerable: true,
  81259. configurable: true
  81260. });
  81261. FramingBehavior.prototype.init = function () {
  81262. // Do notihng
  81263. };
  81264. FramingBehavior.prototype.attach = function (camera) {
  81265. var _this = this;
  81266. this._attachedCamera = camera;
  81267. var scene = this._attachedCamera.getScene();
  81268. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  81269. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81270. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81271. _this._isPointerDown = true;
  81272. return;
  81273. }
  81274. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81275. _this._isPointerDown = false;
  81276. }
  81277. });
  81278. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81279. if (mesh) {
  81280. _this.zoomOnMesh(mesh);
  81281. }
  81282. });
  81283. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81284. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81285. _this._applyUserInteraction();
  81286. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  81287. // back to the default position after a given timeout
  81288. _this._maintainCameraAboveGround();
  81289. });
  81290. };
  81291. FramingBehavior.prototype.detach = function () {
  81292. if (!this._attachedCamera) {
  81293. return;
  81294. }
  81295. var scene = this._attachedCamera.getScene();
  81296. if (this._onPrePointerObservableObserver) {
  81297. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81298. }
  81299. if (this._onAfterCheckInputsObserver) {
  81300. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81301. }
  81302. if (this._onMeshTargetChangedObserver) {
  81303. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81304. }
  81305. this._attachedCamera = null;
  81306. };
  81307. /**
  81308. * Targets the given mesh and updates zoom level accordingly.
  81309. * @param mesh The mesh to target.
  81310. * @param radius Optional. If a cached radius position already exists, overrides default.
  81311. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81312. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81313. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81314. */
  81315. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81316. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81317. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81318. mesh.computeWorldMatrix(true);
  81319. var boundingBox = mesh.getBoundingInfo().boundingBox;
  81320. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  81321. };
  81322. /**
  81323. * Targets the given mesh with its children and updates zoom level accordingly.
  81324. * @param mesh The mesh to target.
  81325. * @param radius Optional. If a cached radius position already exists, overrides default.
  81326. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81327. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81328. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81329. */
  81330. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81331. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81332. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81333. mesh.computeWorldMatrix(true);
  81334. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  81335. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  81336. };
  81337. /**
  81338. * Targets the given meshes with their children and updates zoom level accordingly.
  81339. * @param meshes The mesh to target.
  81340. * @param radius Optional. If a cached radius position already exists, overrides default.
  81341. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81342. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81343. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81344. */
  81345. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  81346. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81347. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81348. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81349. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81350. for (var i = 0; i < meshes.length; i++) {
  81351. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  81352. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  81353. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  81354. }
  81355. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  81356. };
  81357. /**
  81358. * Targets the given mesh and updates zoom level accordingly.
  81359. * @param mesh The mesh to target.
  81360. * @param radius Optional. If a cached radius position already exists, overrides default.
  81361. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81362. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81363. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81364. */
  81365. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  81366. var _this = this;
  81367. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81368. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81369. var zoomTarget;
  81370. if (!this._attachedCamera) {
  81371. return;
  81372. }
  81373. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  81374. var bottom = minimumWorld.y;
  81375. var top = maximumWorld.y;
  81376. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  81377. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  81378. if (focusOnOriginXZ) {
  81379. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  81380. }
  81381. else {
  81382. var centerWorld = minimumWorld.add(radiusWorld);
  81383. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  81384. }
  81385. if (!this._vectorTransition) {
  81386. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  81387. }
  81388. this._betaIsAnimating = true;
  81389. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  81390. if (animatable) {
  81391. this._animatables.push(animatable);
  81392. }
  81393. // sets the radius and lower radius bounds
  81394. // Small delta ensures camera is not always at lower zoom limit.
  81395. var radius = 0;
  81396. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  81397. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81398. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  81399. radius = position;
  81400. }
  81401. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81402. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81403. if (this._attachedCamera.lowerRadiusLimit === null) {
  81404. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  81405. }
  81406. }
  81407. // Set sensibilities
  81408. var extend = maximumWorld.subtract(minimumWorld).length();
  81409. this._attachedCamera.panningSensibility = 5000 / extend;
  81410. this._attachedCamera.wheelPrecision = 100 / radius;
  81411. // transition to new radius
  81412. if (!this._radiusTransition) {
  81413. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81414. }
  81415. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  81416. if (onAnimationEnd) {
  81417. onAnimationEnd();
  81418. }
  81419. if (_this._attachedCamera) {
  81420. _this._attachedCamera.storeState();
  81421. }
  81422. });
  81423. if (animatable) {
  81424. this._animatables.push(animatable);
  81425. }
  81426. };
  81427. /**
  81428. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  81429. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  81430. * frustum width.
  81431. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  81432. * to fully enclose the mesh in the viewing frustum.
  81433. */
  81434. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  81435. var size = maximumWorld.subtract(minimumWorld);
  81436. var boxVectorGlobalDiagonal = size.length();
  81437. var frustumSlope = this._getFrustumSlope();
  81438. // Formula for setting distance
  81439. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  81440. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  81441. // Horizon distance
  81442. var radius = radiusWithoutFraming * this._radiusScale;
  81443. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  81444. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  81445. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  81446. var camera = this._attachedCamera;
  81447. if (!camera) {
  81448. return 0;
  81449. }
  81450. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81451. // Don't exceed the requested limit
  81452. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  81453. }
  81454. // Don't exceed the upper radius limit
  81455. if (camera.upperRadiusLimit) {
  81456. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  81457. }
  81458. return distance;
  81459. };
  81460. /**
  81461. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  81462. * is automatically returned to its default position (expected to be above ground plane).
  81463. */
  81464. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  81465. var _this = this;
  81466. if (this._elevationReturnTime < 0) {
  81467. return;
  81468. }
  81469. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  81470. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  81471. var limitBeta = Math.PI * 0.5;
  81472. // Bring the camera back up if below the ground plane
  81473. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  81474. this._betaIsAnimating = true;
  81475. //Transition to new position
  81476. this.stopAllAnimations();
  81477. if (!this._betaTransition) {
  81478. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81479. }
  81480. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  81481. _this._clearAnimationLocks();
  81482. _this.stopAllAnimations();
  81483. });
  81484. if (animatabe) {
  81485. this._animatables.push(animatabe);
  81486. }
  81487. }
  81488. };
  81489. /**
  81490. * Returns the frustum slope based on the canvas ratio and camera FOV
  81491. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  81492. */
  81493. FramingBehavior.prototype._getFrustumSlope = function () {
  81494. // Calculate the viewport ratio
  81495. // Aspect Ratio is Height/Width.
  81496. var camera = this._attachedCamera;
  81497. if (!camera) {
  81498. return BABYLON.Vector2.Zero();
  81499. }
  81500. var engine = camera.getScene().getEngine();
  81501. var aspectRatio = engine.getAspectRatio(camera);
  81502. // Camera FOV is the vertical field of view (top-bottom) in radians.
  81503. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  81504. var frustumSlopeY = Math.tan(camera.fov / 2);
  81505. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  81506. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  81507. // along the forward vector.
  81508. var frustumSlopeX = frustumSlopeY * aspectRatio;
  81509. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  81510. };
  81511. /**
  81512. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  81513. */
  81514. FramingBehavior.prototype._clearAnimationLocks = function () {
  81515. this._betaIsAnimating = false;
  81516. };
  81517. /**
  81518. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81519. */
  81520. FramingBehavior.prototype._applyUserInteraction = function () {
  81521. if (this.isUserIsMoving) {
  81522. this._lastInteractionTime = BABYLON.Tools.Now;
  81523. this.stopAllAnimations();
  81524. this._clearAnimationLocks();
  81525. }
  81526. };
  81527. /**
  81528. * Stops and removes all animations that have been applied to the camera
  81529. */
  81530. FramingBehavior.prototype.stopAllAnimations = function () {
  81531. if (this._attachedCamera) {
  81532. this._attachedCamera.animations = [];
  81533. }
  81534. while (this._animatables.length) {
  81535. if (this._animatables[0]) {
  81536. this._animatables[0].onAnimationEnd = null;
  81537. this._animatables[0].stop();
  81538. }
  81539. this._animatables.shift();
  81540. }
  81541. };
  81542. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  81543. /**
  81544. * Gets a value indicating if the user is moving the camera
  81545. */
  81546. get: function () {
  81547. if (!this._attachedCamera) {
  81548. return false;
  81549. }
  81550. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81551. this._attachedCamera.inertialBetaOffset !== 0 ||
  81552. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81553. this._attachedCamera.inertialPanningX !== 0 ||
  81554. this._attachedCamera.inertialPanningY !== 0 ||
  81555. this._isPointerDown;
  81556. },
  81557. enumerable: true,
  81558. configurable: true
  81559. });
  81560. /**
  81561. * The easing function used by animations
  81562. */
  81563. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  81564. /**
  81565. * The easing mode used by animations
  81566. */
  81567. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  81568. // Statics
  81569. /**
  81570. * The camera can move all the way towards the mesh.
  81571. */
  81572. FramingBehavior.IgnoreBoundsSizeMode = 0;
  81573. /**
  81574. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  81575. */
  81576. FramingBehavior.FitFrustumSidesMode = 1;
  81577. return FramingBehavior;
  81578. }());
  81579. BABYLON.FramingBehavior = FramingBehavior;
  81580. })(BABYLON || (BABYLON = {}));
  81581. //# sourceMappingURL=babylon.framingBehavior.js.map
  81582. var BABYLON;
  81583. (function (BABYLON) {
  81584. /**
  81585. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  81586. */
  81587. var BouncingBehavior = /** @class */ (function () {
  81588. function BouncingBehavior() {
  81589. /**
  81590. * The duration of the animation, in milliseconds
  81591. */
  81592. this.transitionDuration = 450;
  81593. /**
  81594. * Length of the distance animated by the transition when lower radius is reached
  81595. */
  81596. this.lowerRadiusTransitionRange = 2;
  81597. /**
  81598. * Length of the distance animated by the transition when upper radius is reached
  81599. */
  81600. this.upperRadiusTransitionRange = -2;
  81601. this._autoTransitionRange = false;
  81602. // Animations
  81603. this._radiusIsAnimating = false;
  81604. this._radiusBounceTransition = null;
  81605. this._animatables = new Array();
  81606. }
  81607. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81608. get: function () {
  81609. return "Bouncing";
  81610. },
  81611. enumerable: true,
  81612. configurable: true
  81613. });
  81614. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81615. /**
  81616. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81617. */
  81618. get: function () {
  81619. return this._autoTransitionRange;
  81620. },
  81621. /**
  81622. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81623. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81624. */
  81625. set: function (value) {
  81626. var _this = this;
  81627. if (this._autoTransitionRange === value) {
  81628. return;
  81629. }
  81630. this._autoTransitionRange = value;
  81631. var camera = this._attachedCamera;
  81632. if (!camera) {
  81633. return;
  81634. }
  81635. if (value) {
  81636. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81637. if (!mesh) {
  81638. return;
  81639. }
  81640. mesh.computeWorldMatrix(true);
  81641. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81642. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81643. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81644. });
  81645. }
  81646. else if (this._onMeshTargetChangedObserver) {
  81647. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81648. }
  81649. },
  81650. enumerable: true,
  81651. configurable: true
  81652. });
  81653. BouncingBehavior.prototype.init = function () {
  81654. // Do notihng
  81655. };
  81656. BouncingBehavior.prototype.attach = function (camera) {
  81657. var _this = this;
  81658. this._attachedCamera = camera;
  81659. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81660. if (!_this._attachedCamera) {
  81661. return;
  81662. }
  81663. // Add the bounce animation to the lower radius limit
  81664. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  81665. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  81666. }
  81667. // Add the bounce animation to the upper radius limit
  81668. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  81669. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  81670. }
  81671. });
  81672. };
  81673. BouncingBehavior.prototype.detach = function () {
  81674. if (!this._attachedCamera) {
  81675. return;
  81676. }
  81677. if (this._onAfterCheckInputsObserver) {
  81678. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81679. }
  81680. if (this._onMeshTargetChangedObserver) {
  81681. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81682. }
  81683. this._attachedCamera = null;
  81684. };
  81685. /**
  81686. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  81687. * @param radiusLimit The limit to check against.
  81688. * @return Bool to indicate if at limit.
  81689. */
  81690. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  81691. if (!this._attachedCamera) {
  81692. return false;
  81693. }
  81694. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  81695. return true;
  81696. }
  81697. return false;
  81698. };
  81699. /**
  81700. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  81701. * @param radiusDelta The delta by which to animate to. Can be negative.
  81702. */
  81703. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  81704. var _this = this;
  81705. if (!this._attachedCamera) {
  81706. return;
  81707. }
  81708. if (!this._radiusBounceTransition) {
  81709. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  81710. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  81711. }
  81712. // Prevent zoom until bounce has completed
  81713. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  81714. this._attachedCamera.wheelPrecision = Infinity;
  81715. this._attachedCamera.inertialRadiusOffset = 0;
  81716. // Animate to the radius limit
  81717. this.stopAllAnimations();
  81718. this._radiusIsAnimating = true;
  81719. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  81720. if (animatable) {
  81721. this._animatables.push(animatable);
  81722. }
  81723. };
  81724. /**
  81725. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  81726. */
  81727. BouncingBehavior.prototype._clearAnimationLocks = function () {
  81728. this._radiusIsAnimating = false;
  81729. if (this._attachedCamera) {
  81730. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  81731. }
  81732. };
  81733. /**
  81734. * Stops and removes all animations that have been applied to the camera
  81735. */
  81736. BouncingBehavior.prototype.stopAllAnimations = function () {
  81737. if (this._attachedCamera) {
  81738. this._attachedCamera.animations = [];
  81739. }
  81740. while (this._animatables.length) {
  81741. this._animatables[0].onAnimationEnd = null;
  81742. this._animatables[0].stop();
  81743. this._animatables.shift();
  81744. }
  81745. };
  81746. /**
  81747. * The easing function used by animations
  81748. */
  81749. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  81750. /**
  81751. * The easing mode used by animations
  81752. */
  81753. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  81754. return BouncingBehavior;
  81755. }());
  81756. BABYLON.BouncingBehavior = BouncingBehavior;
  81757. })(BABYLON || (BABYLON = {}));
  81758. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  81759. var BABYLON;
  81760. (function (BABYLON) {
  81761. var AutoRotationBehavior = /** @class */ (function () {
  81762. function AutoRotationBehavior() {
  81763. this._zoomStopsAnimation = false;
  81764. this._idleRotationSpeed = 0.05;
  81765. this._idleRotationWaitTime = 2000;
  81766. this._idleRotationSpinupTime = 2000;
  81767. this._isPointerDown = false;
  81768. this._lastFrameTime = null;
  81769. this._lastInteractionTime = -Infinity;
  81770. this._cameraRotationSpeed = 0;
  81771. this._lastFrameRadius = 0;
  81772. }
  81773. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  81774. get: function () {
  81775. return "AutoRotation";
  81776. },
  81777. enumerable: true,
  81778. configurable: true
  81779. });
  81780. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  81781. /**
  81782. * Gets the flag that indicates if user zooming should stop animation.
  81783. */
  81784. get: function () {
  81785. return this._zoomStopsAnimation;
  81786. },
  81787. /**
  81788. * Sets the flag that indicates if user zooming should stop animation.
  81789. */
  81790. set: function (flag) {
  81791. this._zoomStopsAnimation = flag;
  81792. },
  81793. enumerable: true,
  81794. configurable: true
  81795. });
  81796. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  81797. /**
  81798. * Gets the default speed at which the camera rotates around the model.
  81799. */
  81800. get: function () {
  81801. return this._idleRotationSpeed;
  81802. },
  81803. /**
  81804. * Sets the default speed at which the camera rotates around the model.
  81805. */
  81806. set: function (speed) {
  81807. this._idleRotationSpeed = speed;
  81808. },
  81809. enumerable: true,
  81810. configurable: true
  81811. });
  81812. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  81813. /**
  81814. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  81815. */
  81816. get: function () {
  81817. return this._idleRotationWaitTime;
  81818. },
  81819. /**
  81820. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  81821. */
  81822. set: function (time) {
  81823. this._idleRotationWaitTime = time;
  81824. },
  81825. enumerable: true,
  81826. configurable: true
  81827. });
  81828. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  81829. /**
  81830. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81831. */
  81832. get: function () {
  81833. return this._idleRotationSpinupTime;
  81834. },
  81835. /**
  81836. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81837. */
  81838. set: function (time) {
  81839. this._idleRotationSpinupTime = time;
  81840. },
  81841. enumerable: true,
  81842. configurable: true
  81843. });
  81844. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  81845. /**
  81846. * Gets a value indicating if the camera is currently rotating because of this behavior
  81847. */
  81848. get: function () {
  81849. return Math.abs(this._cameraRotationSpeed) > 0;
  81850. },
  81851. enumerable: true,
  81852. configurable: true
  81853. });
  81854. AutoRotationBehavior.prototype.init = function () {
  81855. // Do notihng
  81856. };
  81857. AutoRotationBehavior.prototype.attach = function (camera) {
  81858. var _this = this;
  81859. this._attachedCamera = camera;
  81860. var scene = this._attachedCamera.getScene();
  81861. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81862. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81863. _this._isPointerDown = true;
  81864. return;
  81865. }
  81866. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81867. _this._isPointerDown = false;
  81868. }
  81869. });
  81870. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81871. var now = BABYLON.Tools.Now;
  81872. var dt = 0;
  81873. if (_this._lastFrameTime != null) {
  81874. dt = now - _this._lastFrameTime;
  81875. }
  81876. _this._lastFrameTime = now;
  81877. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81878. _this._applyUserInteraction();
  81879. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  81880. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  81881. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  81882. // Step camera rotation by rotation speed
  81883. if (_this._attachedCamera) {
  81884. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  81885. }
  81886. });
  81887. };
  81888. AutoRotationBehavior.prototype.detach = function () {
  81889. if (!this._attachedCamera) {
  81890. return;
  81891. }
  81892. var scene = this._attachedCamera.getScene();
  81893. if (this._onPrePointerObservableObserver) {
  81894. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81895. }
  81896. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81897. this._attachedCamera = null;
  81898. };
  81899. /**
  81900. * Returns true if user is scrolling.
  81901. * @return true if user is scrolling.
  81902. */
  81903. AutoRotationBehavior.prototype._userIsZooming = function () {
  81904. if (!this._attachedCamera) {
  81905. return false;
  81906. }
  81907. return this._attachedCamera.inertialRadiusOffset !== 0;
  81908. };
  81909. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  81910. if (!this._attachedCamera) {
  81911. return false;
  81912. }
  81913. var zoomHasHitLimit = false;
  81914. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  81915. zoomHasHitLimit = true;
  81916. }
  81917. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  81918. this._lastFrameRadius = this._attachedCamera.radius;
  81919. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  81920. };
  81921. /**
  81922. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81923. */
  81924. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  81925. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  81926. this._lastInteractionTime = BABYLON.Tools.Now;
  81927. }
  81928. };
  81929. // Tools
  81930. AutoRotationBehavior.prototype._userIsMoving = function () {
  81931. if (!this._attachedCamera) {
  81932. return false;
  81933. }
  81934. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81935. this._attachedCamera.inertialBetaOffset !== 0 ||
  81936. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81937. this._attachedCamera.inertialPanningX !== 0 ||
  81938. this._attachedCamera.inertialPanningY !== 0 ||
  81939. this._isPointerDown;
  81940. };
  81941. return AutoRotationBehavior;
  81942. }());
  81943. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  81944. })(BABYLON || (BABYLON = {}));
  81945. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  81946. var BABYLON;
  81947. (function (BABYLON) {
  81948. var NullEngineOptions = /** @class */ (function () {
  81949. function NullEngineOptions() {
  81950. this.renderWidth = 512;
  81951. this.renderHeight = 256;
  81952. this.textureSize = 512;
  81953. this.deterministicLockstep = false;
  81954. this.lockstepMaxSteps = 4;
  81955. }
  81956. return NullEngineOptions;
  81957. }());
  81958. BABYLON.NullEngineOptions = NullEngineOptions;
  81959. /**
  81960. * The null engine class provides support for headless version of babylon.js.
  81961. * This can be used in server side scenario or for testing purposes
  81962. */
  81963. var NullEngine = /** @class */ (function (_super) {
  81964. __extends(NullEngine, _super);
  81965. function NullEngine(options) {
  81966. if (options === void 0) { options = new NullEngineOptions(); }
  81967. var _this = _super.call(this, null) || this;
  81968. if (options.deterministicLockstep === undefined) {
  81969. options.deterministicLockstep = false;
  81970. }
  81971. if (options.lockstepMaxSteps === undefined) {
  81972. options.lockstepMaxSteps = 4;
  81973. }
  81974. _this._options = options;
  81975. // Init caps
  81976. // We consider we are on a webgl1 capable device
  81977. _this._caps = new BABYLON.EngineCapabilities();
  81978. _this._caps.maxTexturesImageUnits = 16;
  81979. _this._caps.maxVertexTextureImageUnits = 16;
  81980. _this._caps.maxTextureSize = 512;
  81981. _this._caps.maxCubemapTextureSize = 512;
  81982. _this._caps.maxRenderTextureSize = 512;
  81983. _this._caps.maxVertexAttribs = 16;
  81984. _this._caps.maxVaryingVectors = 16;
  81985. _this._caps.maxFragmentUniformVectors = 16;
  81986. _this._caps.maxVertexUniformVectors = 16;
  81987. // Extensions
  81988. _this._caps.standardDerivatives = false;
  81989. _this._caps.astc = null;
  81990. _this._caps.s3tc = null;
  81991. _this._caps.pvrtc = null;
  81992. _this._caps.etc1 = null;
  81993. _this._caps.etc2 = null;
  81994. _this._caps.textureAnisotropicFilterExtension = null;
  81995. _this._caps.maxAnisotropy = 0;
  81996. _this._caps.uintIndices = false;
  81997. _this._caps.fragmentDepthSupported = false;
  81998. _this._caps.highPrecisionShaderSupported = true;
  81999. _this._caps.colorBufferFloat = false;
  82000. _this._caps.textureFloat = false;
  82001. _this._caps.textureFloatLinearFiltering = false;
  82002. _this._caps.textureFloatRender = false;
  82003. _this._caps.textureHalfFloat = false;
  82004. _this._caps.textureHalfFloatLinearFiltering = false;
  82005. _this._caps.textureHalfFloatRender = false;
  82006. _this._caps.textureLOD = false;
  82007. _this._caps.drawBuffersExtension = false;
  82008. _this._caps.depthTextureExtension = false;
  82009. _this._caps.vertexArrayObject = false;
  82010. _this._caps.instancedArrays = false;
  82011. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  82012. // Wrappers
  82013. if (typeof URL === "undefined") {
  82014. URL = {
  82015. createObjectURL: function () { },
  82016. revokeObjectURL: function () { }
  82017. };
  82018. }
  82019. if (typeof Blob === "undefined") {
  82020. Blob = function () { };
  82021. }
  82022. return _this;
  82023. }
  82024. NullEngine.prototype.isDeterministicLockStep = function () {
  82025. return this._options.deterministicLockstep;
  82026. };
  82027. NullEngine.prototype.getLockstepMaxSteps = function () {
  82028. return this._options.lockstepMaxSteps;
  82029. };
  82030. NullEngine.prototype.createVertexBuffer = function (vertices) {
  82031. return {
  82032. capacity: 0,
  82033. references: 1,
  82034. is32Bits: false
  82035. };
  82036. };
  82037. NullEngine.prototype.createIndexBuffer = function (indices) {
  82038. return {
  82039. capacity: 0,
  82040. references: 1,
  82041. is32Bits: false
  82042. };
  82043. };
  82044. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  82045. if (stencil === void 0) { stencil = false; }
  82046. };
  82047. NullEngine.prototype.getRenderWidth = function (useScreen) {
  82048. if (useScreen === void 0) { useScreen = false; }
  82049. if (!useScreen && this._currentRenderTarget) {
  82050. return this._currentRenderTarget.width;
  82051. }
  82052. return this._options.renderWidth;
  82053. };
  82054. NullEngine.prototype.getRenderHeight = function (useScreen) {
  82055. if (useScreen === void 0) { useScreen = false; }
  82056. if (!useScreen && this._currentRenderTarget) {
  82057. return this._currentRenderTarget.height;
  82058. }
  82059. return this._options.renderHeight;
  82060. };
  82061. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  82062. this._cachedViewport = viewport;
  82063. };
  82064. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  82065. return {
  82066. transformFeedback: null,
  82067. __SPECTOR_rebuildProgram: null
  82068. };
  82069. };
  82070. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  82071. return [];
  82072. };
  82073. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  82074. return [];
  82075. };
  82076. NullEngine.prototype.bindSamplers = function (effect) {
  82077. this._currentEffect = null;
  82078. };
  82079. NullEngine.prototype.enableEffect = function (effect) {
  82080. this._currentEffect = effect;
  82081. if (effect.onBind) {
  82082. effect.onBind(effect);
  82083. }
  82084. effect.onBindObservable.notifyObservers(effect);
  82085. };
  82086. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  82087. if (zOffset === void 0) { zOffset = 0; }
  82088. if (reverseSide === void 0) { reverseSide = false; }
  82089. };
  82090. NullEngine.prototype.setIntArray = function (uniform, array) {
  82091. };
  82092. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  82093. };
  82094. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  82095. };
  82096. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  82097. };
  82098. NullEngine.prototype.setFloatArray = function (uniform, array) {
  82099. };
  82100. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  82101. };
  82102. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  82103. };
  82104. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  82105. };
  82106. NullEngine.prototype.setArray = function (uniform, array) {
  82107. };
  82108. NullEngine.prototype.setArray2 = function (uniform, array) {
  82109. };
  82110. NullEngine.prototype.setArray3 = function (uniform, array) {
  82111. };
  82112. NullEngine.prototype.setArray4 = function (uniform, array) {
  82113. };
  82114. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  82115. };
  82116. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  82117. };
  82118. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  82119. };
  82120. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  82121. };
  82122. NullEngine.prototype.setFloat = function (uniform, value) {
  82123. };
  82124. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  82125. };
  82126. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  82127. };
  82128. NullEngine.prototype.setBool = function (uniform, bool) {
  82129. };
  82130. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  82131. };
  82132. NullEngine.prototype.setColor3 = function (uniform, color3) {
  82133. };
  82134. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  82135. };
  82136. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  82137. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  82138. if (this._alphaMode === mode) {
  82139. return;
  82140. }
  82141. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  82142. if (!noDepthWriteChange) {
  82143. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  82144. }
  82145. this._alphaMode = mode;
  82146. };
  82147. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  82148. };
  82149. NullEngine.prototype.wipeCaches = function (bruteForce) {
  82150. if (this.preventCacheWipeBetweenFrames) {
  82151. return;
  82152. }
  82153. this.resetTextureCache();
  82154. this._currentEffect = null;
  82155. if (bruteForce) {
  82156. this._currentProgram = null;
  82157. this._stencilState.reset();
  82158. this._depthCullingState.reset();
  82159. this.setDepthFunctionToLessOrEqual();
  82160. this._alphaState.reset();
  82161. }
  82162. this._cachedVertexBuffers = null;
  82163. this._cachedIndexBuffer = null;
  82164. this._cachedEffectForVertexBuffers = null;
  82165. };
  82166. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  82167. };
  82168. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  82169. };
  82170. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  82171. };
  82172. NullEngine.prototype._createTexture = function () {
  82173. return {};
  82174. };
  82175. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  82176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  82177. if (onLoad === void 0) { onLoad = null; }
  82178. if (onError === void 0) { onError = null; }
  82179. if (buffer === void 0) { buffer = null; }
  82180. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  82181. var url = String(urlArg);
  82182. texture.url = url;
  82183. texture.generateMipMaps = !noMipmap;
  82184. texture.samplingMode = samplingMode;
  82185. texture.invertY = invertY;
  82186. texture.baseWidth = this._options.textureSize;
  82187. texture.baseHeight = this._options.textureSize;
  82188. texture.width = this._options.textureSize;
  82189. texture.height = this._options.textureSize;
  82190. if (format) {
  82191. texture.format = format;
  82192. }
  82193. texture.isReady = true;
  82194. if (onLoad) {
  82195. onLoad();
  82196. }
  82197. return texture;
  82198. };
  82199. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  82200. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  82201. if (options !== undefined && typeof options === "object") {
  82202. fullOptions.generateMipMaps = options.generateMipMaps;
  82203. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  82204. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  82205. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  82206. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  82207. }
  82208. else {
  82209. fullOptions.generateMipMaps = options;
  82210. fullOptions.generateDepthBuffer = true;
  82211. fullOptions.generateStencilBuffer = false;
  82212. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82213. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82214. }
  82215. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  82216. var width = size.width || size;
  82217. var height = size.height || size;
  82218. texture._depthStencilBuffer = {};
  82219. texture._framebuffer = {};
  82220. texture.baseWidth = width;
  82221. texture.baseHeight = height;
  82222. texture.width = width;
  82223. texture.height = height;
  82224. texture.isReady = true;
  82225. texture.samples = 1;
  82226. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  82227. texture.samplingMode = fullOptions.samplingMode;
  82228. texture.type = fullOptions.type;
  82229. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  82230. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  82231. return texture;
  82232. };
  82233. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  82234. texture.samplingMode = samplingMode;
  82235. };
  82236. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  82237. if (this._currentRenderTarget) {
  82238. this.unBindFramebuffer(this._currentRenderTarget);
  82239. }
  82240. this._currentRenderTarget = texture;
  82241. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  82242. if (this._cachedViewport && !forceFullscreenViewport) {
  82243. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  82244. }
  82245. };
  82246. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  82247. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  82248. this._currentRenderTarget = null;
  82249. if (onBeforeUnbind) {
  82250. if (texture._MSAAFramebuffer) {
  82251. this._currentFramebuffer = texture._framebuffer;
  82252. }
  82253. onBeforeUnbind();
  82254. }
  82255. this._currentFramebuffer = null;
  82256. };
  82257. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  82258. var vbo = {
  82259. capacity: 1,
  82260. references: 1,
  82261. is32Bits: false
  82262. };
  82263. return vbo;
  82264. };
  82265. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  82266. if (offset === void 0) { offset = 0; }
  82267. };
  82268. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  82269. };
  82270. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  82271. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  82272. this._boundTexturesCache[this._activeChannel] = texture;
  82273. }
  82274. };
  82275. NullEngine.prototype._bindTexture = function (channel, texture) {
  82276. if (channel < 0) {
  82277. return;
  82278. }
  82279. this._bindTextureDirectly(0, texture);
  82280. };
  82281. NullEngine.prototype._releaseBuffer = function (buffer) {
  82282. buffer.references--;
  82283. if (buffer.references === 0) {
  82284. return true;
  82285. }
  82286. return false;
  82287. };
  82288. return NullEngine;
  82289. }(BABYLON.Engine));
  82290. BABYLON.NullEngine = NullEngine;
  82291. })(BABYLON || (BABYLON = {}));
  82292. //# sourceMappingURL=babylon.nullEngine.js.map
  82293. var BABYLON;
  82294. (function (BABYLON) {
  82295. /**
  82296. * This class can be used to get instrumentation data from a Babylon engine
  82297. */
  82298. var EngineInstrumentation = /** @class */ (function () {
  82299. function EngineInstrumentation(engine) {
  82300. this.engine = engine;
  82301. this._captureGPUFrameTime = false;
  82302. this._gpuFrameTime = new BABYLON.PerfCounter();
  82303. this._captureShaderCompilationTime = false;
  82304. this._shaderCompilationTime = new BABYLON.PerfCounter();
  82305. // Observers
  82306. this._onBeginFrameObserver = null;
  82307. this._onEndFrameObserver = null;
  82308. this._onBeforeShaderCompilationObserver = null;
  82309. this._onAfterShaderCompilationObserver = null;
  82310. }
  82311. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  82312. // Properties
  82313. /**
  82314. * Gets the perf counter used for GPU frame time
  82315. */
  82316. get: function () {
  82317. return this._gpuFrameTime;
  82318. },
  82319. enumerable: true,
  82320. configurable: true
  82321. });
  82322. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  82323. /**
  82324. * Gets the GPU frame time capture status
  82325. */
  82326. get: function () {
  82327. return this._captureGPUFrameTime;
  82328. },
  82329. /**
  82330. * Enable or disable the GPU frame time capture
  82331. */
  82332. set: function (value) {
  82333. var _this = this;
  82334. if (value === this._captureGPUFrameTime) {
  82335. return;
  82336. }
  82337. this._captureGPUFrameTime = value;
  82338. if (value) {
  82339. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  82340. if (!_this._gpuFrameTimeToken) {
  82341. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  82342. }
  82343. });
  82344. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  82345. if (!_this._gpuFrameTimeToken) {
  82346. return;
  82347. }
  82348. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  82349. if (time > -1) {
  82350. _this._gpuFrameTimeToken = null;
  82351. _this._gpuFrameTime.fetchNewFrame();
  82352. _this._gpuFrameTime.addCount(time, true);
  82353. }
  82354. });
  82355. }
  82356. else {
  82357. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82358. this._onBeginFrameObserver = null;
  82359. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82360. this._onEndFrameObserver = null;
  82361. }
  82362. },
  82363. enumerable: true,
  82364. configurable: true
  82365. });
  82366. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  82367. /**
  82368. * Gets the perf counter used for shader compilation time
  82369. */
  82370. get: function () {
  82371. return this._shaderCompilationTime;
  82372. },
  82373. enumerable: true,
  82374. configurable: true
  82375. });
  82376. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  82377. /**
  82378. * Gets the shader compilation time capture status
  82379. */
  82380. get: function () {
  82381. return this._captureShaderCompilationTime;
  82382. },
  82383. /**
  82384. * Enable or disable the shader compilation time capture
  82385. */
  82386. set: function (value) {
  82387. var _this = this;
  82388. if (value === this._captureShaderCompilationTime) {
  82389. return;
  82390. }
  82391. this._captureShaderCompilationTime = value;
  82392. if (value) {
  82393. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  82394. _this._shaderCompilationTime.fetchNewFrame();
  82395. _this._shaderCompilationTime.beginMonitoring();
  82396. });
  82397. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  82398. _this._shaderCompilationTime.endMonitoring();
  82399. });
  82400. }
  82401. else {
  82402. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82403. this._onBeforeShaderCompilationObserver = null;
  82404. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82405. this._onAfterShaderCompilationObserver = null;
  82406. }
  82407. },
  82408. enumerable: true,
  82409. configurable: true
  82410. });
  82411. EngineInstrumentation.prototype.dispose = function () {
  82412. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82413. this._onBeginFrameObserver = null;
  82414. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82415. this._onEndFrameObserver = null;
  82416. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82417. this._onBeforeShaderCompilationObserver = null;
  82418. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82419. this._onAfterShaderCompilationObserver = null;
  82420. this.engine = null;
  82421. };
  82422. return EngineInstrumentation;
  82423. }());
  82424. BABYLON.EngineInstrumentation = EngineInstrumentation;
  82425. })(BABYLON || (BABYLON = {}));
  82426. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  82427. var BABYLON;
  82428. (function (BABYLON) {
  82429. /**
  82430. * This class can be used to get instrumentation data from a Babylon engine
  82431. */
  82432. var SceneInstrumentation = /** @class */ (function () {
  82433. function SceneInstrumentation(scene) {
  82434. var _this = this;
  82435. this.scene = scene;
  82436. this._captureActiveMeshesEvaluationTime = false;
  82437. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  82438. this._captureRenderTargetsRenderTime = false;
  82439. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  82440. this._captureFrameTime = false;
  82441. this._frameTime = new BABYLON.PerfCounter();
  82442. this._captureRenderTime = false;
  82443. this._renderTime = new BABYLON.PerfCounter();
  82444. this._captureInterFrameTime = false;
  82445. this._interFrameTime = new BABYLON.PerfCounter();
  82446. this._captureParticlesRenderTime = false;
  82447. this._particlesRenderTime = new BABYLON.PerfCounter();
  82448. this._captureSpritesRenderTime = false;
  82449. this._spritesRenderTime = new BABYLON.PerfCounter();
  82450. this._capturePhysicsTime = false;
  82451. this._physicsTime = new BABYLON.PerfCounter();
  82452. this._captureAnimationsTime = false;
  82453. this._animationsTime = new BABYLON.PerfCounter();
  82454. // Observers
  82455. this._onBeforeActiveMeshesEvaluationObserver = null;
  82456. this._onAfterActiveMeshesEvaluationObserver = null;
  82457. this._onBeforeRenderTargetsRenderObserver = null;
  82458. this._onAfterRenderTargetsRenderObserver = null;
  82459. this._onAfterRenderObserver = null;
  82460. this._onBeforeDrawPhaseObserver = null;
  82461. this._onAfterDrawPhaseObserver = null;
  82462. this._onBeforeAnimationsObserver = null;
  82463. this._onBeforeParticlesRenderingObserver = null;
  82464. this._onAfterParticlesRenderingObserver = null;
  82465. this._onBeforeSpritesRenderingObserver = null;
  82466. this._onAfterSpritesRenderingObserver = null;
  82467. this._onBeforePhysicsObserver = null;
  82468. this._onAfterPhysicsObserver = null;
  82469. this._onAfterAnimationsObserver = null;
  82470. // Before render
  82471. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  82472. if (_this._captureActiveMeshesEvaluationTime) {
  82473. _this._activeMeshesEvaluationTime.fetchNewFrame();
  82474. }
  82475. if (_this._captureRenderTargetsRenderTime) {
  82476. _this._renderTargetsRenderTime.fetchNewFrame();
  82477. }
  82478. if (_this._captureFrameTime) {
  82479. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  82480. _this._frameTime.beginMonitoring();
  82481. }
  82482. if (_this._captureInterFrameTime) {
  82483. _this._interFrameTime.endMonitoring();
  82484. }
  82485. if (_this._captureParticlesRenderTime) {
  82486. _this._particlesRenderTime.fetchNewFrame();
  82487. }
  82488. if (_this._captureSpritesRenderTime) {
  82489. _this._spritesRenderTime.fetchNewFrame();
  82490. }
  82491. if (_this._captureAnimationsTime) {
  82492. _this._animationsTime.beginMonitoring();
  82493. }
  82494. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  82495. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  82496. });
  82497. // After render
  82498. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  82499. if (_this._captureFrameTime) {
  82500. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  82501. _this._frameTime.endMonitoring();
  82502. }
  82503. if (_this._captureRenderTime) {
  82504. _this._renderTime.endMonitoring(false);
  82505. }
  82506. if (_this._captureInterFrameTime) {
  82507. _this._interFrameTime.beginMonitoring();
  82508. }
  82509. });
  82510. }
  82511. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  82512. // Properties
  82513. /**
  82514. * Gets the perf counter used for active meshes evaluation time
  82515. */
  82516. get: function () {
  82517. return this._activeMeshesEvaluationTime;
  82518. },
  82519. enumerable: true,
  82520. configurable: true
  82521. });
  82522. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  82523. /**
  82524. * Gets the active meshes evaluation time capture status
  82525. */
  82526. get: function () {
  82527. return this._captureActiveMeshesEvaluationTime;
  82528. },
  82529. /**
  82530. * Enable or disable the active meshes evaluation time capture
  82531. */
  82532. set: function (value) {
  82533. var _this = this;
  82534. if (value === this._captureActiveMeshesEvaluationTime) {
  82535. return;
  82536. }
  82537. this._captureActiveMeshesEvaluationTime = value;
  82538. if (value) {
  82539. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  82540. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  82541. _this._activeMeshesEvaluationTime.beginMonitoring();
  82542. });
  82543. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  82544. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  82545. _this._activeMeshesEvaluationTime.endMonitoring();
  82546. });
  82547. }
  82548. else {
  82549. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82550. this._onBeforeActiveMeshesEvaluationObserver = null;
  82551. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82552. this._onAfterActiveMeshesEvaluationObserver = null;
  82553. }
  82554. },
  82555. enumerable: true,
  82556. configurable: true
  82557. });
  82558. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  82559. /**
  82560. * Gets the perf counter used for render targets render time
  82561. */
  82562. get: function () {
  82563. return this._renderTargetsRenderTime;
  82564. },
  82565. enumerable: true,
  82566. configurable: true
  82567. });
  82568. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  82569. /**
  82570. * Gets the render targets render time capture status
  82571. */
  82572. get: function () {
  82573. return this._captureRenderTargetsRenderTime;
  82574. },
  82575. /**
  82576. * Enable or disable the render targets render time capture
  82577. */
  82578. set: function (value) {
  82579. var _this = this;
  82580. if (value === this._captureRenderTargetsRenderTime) {
  82581. return;
  82582. }
  82583. this._captureRenderTargetsRenderTime = value;
  82584. if (value) {
  82585. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  82586. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  82587. _this._renderTargetsRenderTime.beginMonitoring();
  82588. });
  82589. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  82590. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  82591. _this._renderTargetsRenderTime.endMonitoring(false);
  82592. });
  82593. }
  82594. else {
  82595. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82596. this._onBeforeRenderTargetsRenderObserver = null;
  82597. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82598. this._onAfterRenderTargetsRenderObserver = null;
  82599. }
  82600. },
  82601. enumerable: true,
  82602. configurable: true
  82603. });
  82604. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  82605. /**
  82606. * Gets the perf counter used for particles render time
  82607. */
  82608. get: function () {
  82609. return this._particlesRenderTime;
  82610. },
  82611. enumerable: true,
  82612. configurable: true
  82613. });
  82614. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  82615. /**
  82616. * Gets the particles render time capture status
  82617. */
  82618. get: function () {
  82619. return this._captureParticlesRenderTime;
  82620. },
  82621. /**
  82622. * Enable or disable the particles render time capture
  82623. */
  82624. set: function (value) {
  82625. var _this = this;
  82626. if (value === this._captureParticlesRenderTime) {
  82627. return;
  82628. }
  82629. this._captureParticlesRenderTime = value;
  82630. if (value) {
  82631. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  82632. BABYLON.Tools.StartPerformanceCounter("Particles");
  82633. _this._particlesRenderTime.beginMonitoring();
  82634. });
  82635. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  82636. BABYLON.Tools.EndPerformanceCounter("Particles");
  82637. _this._particlesRenderTime.endMonitoring(false);
  82638. });
  82639. }
  82640. else {
  82641. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82642. this._onBeforeParticlesRenderingObserver = null;
  82643. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82644. this._onAfterParticlesRenderingObserver = null;
  82645. }
  82646. },
  82647. enumerable: true,
  82648. configurable: true
  82649. });
  82650. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  82651. /**
  82652. * Gets the perf counter used for sprites render time
  82653. */
  82654. get: function () {
  82655. return this._spritesRenderTime;
  82656. },
  82657. enumerable: true,
  82658. configurable: true
  82659. });
  82660. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  82661. /**
  82662. * Gets the sprites render time capture status
  82663. */
  82664. get: function () {
  82665. return this._captureSpritesRenderTime;
  82666. },
  82667. /**
  82668. * Enable or disable the sprites render time capture
  82669. */
  82670. set: function (value) {
  82671. var _this = this;
  82672. if (value === this._captureSpritesRenderTime) {
  82673. return;
  82674. }
  82675. this._captureSpritesRenderTime = value;
  82676. if (value) {
  82677. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  82678. BABYLON.Tools.StartPerformanceCounter("Sprites");
  82679. _this._spritesRenderTime.beginMonitoring();
  82680. });
  82681. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  82682. BABYLON.Tools.EndPerformanceCounter("Sprites");
  82683. _this._spritesRenderTime.endMonitoring(false);
  82684. });
  82685. }
  82686. else {
  82687. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82688. this._onBeforeSpritesRenderingObserver = null;
  82689. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82690. this._onAfterSpritesRenderingObserver = null;
  82691. }
  82692. },
  82693. enumerable: true,
  82694. configurable: true
  82695. });
  82696. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  82697. /**
  82698. * Gets the perf counter used for physics time
  82699. */
  82700. get: function () {
  82701. return this._physicsTime;
  82702. },
  82703. enumerable: true,
  82704. configurable: true
  82705. });
  82706. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  82707. /**
  82708. * Gets the physics time capture status
  82709. */
  82710. get: function () {
  82711. return this._capturePhysicsTime;
  82712. },
  82713. /**
  82714. * Enable or disable the physics time capture
  82715. */
  82716. set: function (value) {
  82717. var _this = this;
  82718. if (value === this._capturePhysicsTime) {
  82719. return;
  82720. }
  82721. this._capturePhysicsTime = value;
  82722. if (value) {
  82723. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  82724. BABYLON.Tools.StartPerformanceCounter("Physics");
  82725. _this._physicsTime.beginMonitoring();
  82726. });
  82727. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  82728. BABYLON.Tools.EndPerformanceCounter("Physics");
  82729. _this._physicsTime.endMonitoring();
  82730. });
  82731. }
  82732. else {
  82733. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82734. this._onBeforePhysicsObserver = null;
  82735. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82736. this._onAfterPhysicsObserver = null;
  82737. }
  82738. },
  82739. enumerable: true,
  82740. configurable: true
  82741. });
  82742. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  82743. /**
  82744. * Gets the perf counter used for animations time
  82745. */
  82746. get: function () {
  82747. return this._animationsTime;
  82748. },
  82749. enumerable: true,
  82750. configurable: true
  82751. });
  82752. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  82753. /**
  82754. * Gets the animations time capture status
  82755. */
  82756. get: function () {
  82757. return this._captureAnimationsTime;
  82758. },
  82759. /**
  82760. * Enable or disable the animations time capture
  82761. */
  82762. set: function (value) {
  82763. var _this = this;
  82764. if (value === this._captureAnimationsTime) {
  82765. return;
  82766. }
  82767. this._captureAnimationsTime = value;
  82768. if (value) {
  82769. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  82770. _this._animationsTime.endMonitoring();
  82771. });
  82772. }
  82773. else {
  82774. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82775. this._onAfterAnimationsObserver = null;
  82776. }
  82777. },
  82778. enumerable: true,
  82779. configurable: true
  82780. });
  82781. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  82782. /**
  82783. * Gets the perf counter used for frame time capture
  82784. */
  82785. get: function () {
  82786. return this._frameTime;
  82787. },
  82788. enumerable: true,
  82789. configurable: true
  82790. });
  82791. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  82792. /**
  82793. * Gets the frame time capture status
  82794. */
  82795. get: function () {
  82796. return this._captureFrameTime;
  82797. },
  82798. /**
  82799. * Enable or disable the frame time capture
  82800. */
  82801. set: function (value) {
  82802. this._captureFrameTime = value;
  82803. },
  82804. enumerable: true,
  82805. configurable: true
  82806. });
  82807. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  82808. /**
  82809. * Gets the perf counter used for inter-frames time capture
  82810. */
  82811. get: function () {
  82812. return this._interFrameTime;
  82813. },
  82814. enumerable: true,
  82815. configurable: true
  82816. });
  82817. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  82818. /**
  82819. * Gets the inter-frames time capture status
  82820. */
  82821. get: function () {
  82822. return this._captureInterFrameTime;
  82823. },
  82824. /**
  82825. * Enable or disable the inter-frames time capture
  82826. */
  82827. set: function (value) {
  82828. this._captureInterFrameTime = value;
  82829. },
  82830. enumerable: true,
  82831. configurable: true
  82832. });
  82833. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  82834. /**
  82835. * Gets the perf counter used for render time capture
  82836. */
  82837. get: function () {
  82838. return this._renderTime;
  82839. },
  82840. enumerable: true,
  82841. configurable: true
  82842. });
  82843. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  82844. /**
  82845. * Gets the render time capture status
  82846. */
  82847. get: function () {
  82848. return this._captureRenderTime;
  82849. },
  82850. /**
  82851. * Enable or disable the render time capture
  82852. */
  82853. set: function (value) {
  82854. var _this = this;
  82855. if (value === this._captureRenderTime) {
  82856. return;
  82857. }
  82858. this._captureRenderTime = value;
  82859. if (value) {
  82860. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  82861. _this._renderTime.beginMonitoring();
  82862. BABYLON.Tools.StartPerformanceCounter("Main render");
  82863. });
  82864. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  82865. _this._renderTime.endMonitoring(false);
  82866. BABYLON.Tools.EndPerformanceCounter("Main render");
  82867. });
  82868. }
  82869. else {
  82870. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82871. this._onBeforeDrawPhaseObserver = null;
  82872. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82873. this._onAfterDrawPhaseObserver = null;
  82874. }
  82875. },
  82876. enumerable: true,
  82877. configurable: true
  82878. });
  82879. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  82880. /**
  82881. * Gets the perf counter used for draw calls
  82882. */
  82883. get: function () {
  82884. return this.scene.getEngine()._drawCalls;
  82885. },
  82886. enumerable: true,
  82887. configurable: true
  82888. });
  82889. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  82890. /**
  82891. * Gets the perf counter used for texture collisions
  82892. */
  82893. get: function () {
  82894. return this.scene.getEngine()._textureCollisions;
  82895. },
  82896. enumerable: true,
  82897. configurable: true
  82898. });
  82899. SceneInstrumentation.prototype.dispose = function () {
  82900. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  82901. this._onAfterRenderObserver = null;
  82902. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82903. this._onBeforeActiveMeshesEvaluationObserver = null;
  82904. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82905. this._onAfterActiveMeshesEvaluationObserver = null;
  82906. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82907. this._onBeforeRenderTargetsRenderObserver = null;
  82908. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82909. this._onAfterRenderTargetsRenderObserver = null;
  82910. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  82911. this._onBeforeAnimationsObserver = null;
  82912. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82913. this._onBeforeParticlesRenderingObserver = null;
  82914. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82915. this._onAfterParticlesRenderingObserver = null;
  82916. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82917. this._onBeforeSpritesRenderingObserver = null;
  82918. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82919. this._onAfterSpritesRenderingObserver = null;
  82920. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82921. this._onBeforeDrawPhaseObserver = null;
  82922. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82923. this._onAfterDrawPhaseObserver = null;
  82924. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82925. this._onBeforePhysicsObserver = null;
  82926. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82927. this._onAfterPhysicsObserver = null;
  82928. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82929. this._onAfterAnimationsObserver = null;
  82930. this.scene = null;
  82931. };
  82932. return SceneInstrumentation;
  82933. }());
  82934. BABYLON.SceneInstrumentation = SceneInstrumentation;
  82935. })(BABYLON || (BABYLON = {}));
  82936. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  82937. var BABYLON;
  82938. (function (BABYLON) {
  82939. var _TimeToken = /** @class */ (function () {
  82940. function _TimeToken() {
  82941. this._timeElapsedQueryEnded = false;
  82942. }
  82943. return _TimeToken;
  82944. }());
  82945. BABYLON._TimeToken = _TimeToken;
  82946. })(BABYLON || (BABYLON = {}));
  82947. //# sourceMappingURL=babylon.timeToken.js.map
  82948. var BABYLON;
  82949. (function (BABYLON) {
  82950. /**
  82951. * Background material defines definition.
  82952. */
  82953. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  82954. __extends(BackgroundMaterialDefines, _super);
  82955. /**
  82956. * Constructor of the defines.
  82957. */
  82958. function BackgroundMaterialDefines() {
  82959. var _this = _super.call(this) || this;
  82960. /**
  82961. * True if the diffuse texture is in use.
  82962. */
  82963. _this.DIFFUSE = false;
  82964. /**
  82965. * The direct UV channel to use.
  82966. */
  82967. _this.DIFFUSEDIRECTUV = 0;
  82968. /**
  82969. * True if the diffuse texture is in gamma space.
  82970. */
  82971. _this.GAMMADIFFUSE = false;
  82972. /**
  82973. * True if the diffuse texture has opacity in the alpha channel.
  82974. */
  82975. _this.DIFFUSEHASALPHA = false;
  82976. /**
  82977. * True if you want the material to fade to transparent at grazing angle.
  82978. */
  82979. _this.OPACITYFRESNEL = false;
  82980. /**
  82981. * True if an extra blur needs to be added in the reflection.
  82982. */
  82983. _this.REFLECTIONBLUR = false;
  82984. /**
  82985. * True if you want the material to fade to reflection at grazing angle.
  82986. */
  82987. _this.REFLECTIONFRESNEL = false;
  82988. /**
  82989. * True if you want the material to falloff as far as you move away from the scene center.
  82990. */
  82991. _this.REFLECTIONFALLOFF = false;
  82992. /**
  82993. * False if the current Webgl implementation does not support the texture lod extension.
  82994. */
  82995. _this.TEXTURELODSUPPORT = false;
  82996. /**
  82997. * True to ensure the data are premultiplied.
  82998. */
  82999. _this.PREMULTIPLYALPHA = false;
  83000. /**
  83001. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  83002. */
  83003. _this.USERGBCOLOR = false;
  83004. /**
  83005. * True to add noise in order to reduce the banding effect.
  83006. */
  83007. _this.NOISE = false;
  83008. // Image Processing Configuration.
  83009. _this.IMAGEPROCESSING = false;
  83010. _this.VIGNETTE = false;
  83011. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83012. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83013. _this.TONEMAPPING = false;
  83014. _this.CONTRAST = false;
  83015. _this.COLORCURVES = false;
  83016. _this.COLORGRADING = false;
  83017. _this.COLORGRADING3D = false;
  83018. _this.SAMPLER3DGREENDEPTH = false;
  83019. _this.SAMPLER3DBGRMAP = false;
  83020. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83021. _this.EXPOSURE = false;
  83022. // Reflection.
  83023. _this.REFLECTION = false;
  83024. _this.REFLECTIONMAP_3D = false;
  83025. _this.REFLECTIONMAP_SPHERICAL = false;
  83026. _this.REFLECTIONMAP_PLANAR = false;
  83027. _this.REFLECTIONMAP_CUBIC = false;
  83028. _this.REFLECTIONMAP_PROJECTION = false;
  83029. _this.REFLECTIONMAP_SKYBOX = false;
  83030. _this.REFLECTIONMAP_EXPLICIT = false;
  83031. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83032. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83033. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83034. _this.INVERTCUBICMAP = false;
  83035. _this.REFLECTIONMAP_OPPOSITEZ = false;
  83036. _this.LODINREFLECTIONALPHA = false;
  83037. _this.GAMMAREFLECTION = false;
  83038. // Default BJS.
  83039. _this.MAINUV1 = false;
  83040. _this.MAINUV2 = false;
  83041. _this.UV1 = false;
  83042. _this.UV2 = false;
  83043. _this.CLIPPLANE = false;
  83044. _this.POINTSIZE = false;
  83045. _this.FOG = false;
  83046. _this.NORMAL = false;
  83047. _this.NUM_BONE_INFLUENCERS = 0;
  83048. _this.BonesPerMesh = 0;
  83049. _this.INSTANCES = false;
  83050. _this.SHADOWFLOAT = false;
  83051. _this.rebuild();
  83052. return _this;
  83053. }
  83054. return BackgroundMaterialDefines;
  83055. }(BABYLON.MaterialDefines));
  83056. /**
  83057. * Background material used to create an efficient environement around your scene.
  83058. */
  83059. var BackgroundMaterial = /** @class */ (function (_super) {
  83060. __extends(BackgroundMaterial, _super);
  83061. /**
  83062. * constructor
  83063. * @param name The name of the material
  83064. * @param scene The scene to add the material to
  83065. */
  83066. function BackgroundMaterial(name, scene) {
  83067. var _this = _super.call(this, name, scene) || this;
  83068. _this.primaryColor = BABYLON.Color3.White();
  83069. _this.primaryLevel = 1;
  83070. _this.secondaryColor = BABYLON.Color3.Gray();
  83071. _this.secondaryLevel = 1;
  83072. _this.tertiaryColor = BABYLON.Color3.Black();
  83073. _this.tertiaryLevel = 1;
  83074. _this.reflectionTexture = null;
  83075. _this.reflectionBlur = 0;
  83076. _this.diffuseTexture = null;
  83077. /**
  83078. * Specify the list of lights casting shadow on the material.
  83079. * All scene shadow lights will be included if null.
  83080. */
  83081. _this._shadowLights = null;
  83082. _this.shadowLights = null;
  83083. _this.shadowBlurScale = 1;
  83084. _this.shadowLevel = 0;
  83085. _this.sceneCenter = BABYLON.Vector3.Zero();
  83086. _this.opacityFresnel = true;
  83087. _this.reflectionFresnel = false;
  83088. _this.reflectionFalloffDistance = 0.0;
  83089. _this.reflectionAmount = 1.0;
  83090. _this.reflectionReflectance0 = 0.05;
  83091. _this.reflectionReflectance90 = 0.5;
  83092. _this.useRGBColor = true;
  83093. _this.enableNoise = false;
  83094. /**
  83095. * Number of Simultaneous lights allowed on the material.
  83096. */
  83097. _this._maxSimultaneousLights = 4;
  83098. _this.maxSimultaneousLights = 4;
  83099. /**
  83100. * Keep track of the image processing observer to allow dispose and replace.
  83101. */
  83102. _this._imageProcessingObserver = null;
  83103. // Temp values kept as cache in the material.
  83104. _this._renderTargets = new BABYLON.SmartArray(16);
  83105. _this._reflectionControls = BABYLON.Vector4.Zero();
  83106. // Setup the default processing configuration to the scene.
  83107. _this._attachImageProcessingConfiguration(null);
  83108. _this.getRenderTargetTextures = function () {
  83109. _this._renderTargets.reset();
  83110. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  83111. _this._renderTargets.push(_this._diffuseTexture);
  83112. }
  83113. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  83114. _this._renderTargets.push(_this._reflectionTexture);
  83115. }
  83116. return _this._renderTargets;
  83117. };
  83118. return _this;
  83119. }
  83120. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  83121. /**
  83122. * Sets the reflection reflectance fresnel values according to the default standard
  83123. * empirically know to work well :-)
  83124. */
  83125. set: function (value) {
  83126. var reflectionWeight = value;
  83127. if (reflectionWeight < 0.5) {
  83128. reflectionWeight = reflectionWeight * 2.0;
  83129. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  83130. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  83131. }
  83132. else {
  83133. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  83134. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  83135. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  83136. }
  83137. },
  83138. enumerable: true,
  83139. configurable: true
  83140. });
  83141. /**
  83142. * Attaches a new image processing configuration to the PBR Material.
  83143. * @param configuration (if null the scene configuration will be use)
  83144. */
  83145. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  83146. var _this = this;
  83147. if (configuration === this._imageProcessingConfiguration) {
  83148. return;
  83149. }
  83150. // Detaches observer.
  83151. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83152. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83153. }
  83154. // Pick the scene configuration if needed.
  83155. if (!configuration) {
  83156. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  83157. }
  83158. else {
  83159. this._imageProcessingConfiguration = configuration;
  83160. }
  83161. // Attaches observer.
  83162. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83163. _this._markAllSubMeshesAsImageProcessingDirty();
  83164. });
  83165. };
  83166. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  83167. /**
  83168. * Gets the image processing configuration used either in this material.
  83169. */
  83170. get: function () {
  83171. return this._imageProcessingConfiguration;
  83172. },
  83173. /**
  83174. * Sets the Default image processing configuration used either in the this material.
  83175. *
  83176. * If sets to null, the scene one is in use.
  83177. */
  83178. set: function (value) {
  83179. this._attachImageProcessingConfiguration(value);
  83180. // Ensure the effect will be rebuilt.
  83181. this._markAllSubMeshesAsTexturesDirty();
  83182. },
  83183. enumerable: true,
  83184. configurable: true
  83185. });
  83186. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  83187. /**
  83188. * Gets wether the color curves effect is enabled.
  83189. */
  83190. get: function () {
  83191. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83192. },
  83193. /**
  83194. * Sets wether the color curves effect is enabled.
  83195. */
  83196. set: function (value) {
  83197. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83198. },
  83199. enumerable: true,
  83200. configurable: true
  83201. });
  83202. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  83203. /**
  83204. * Gets wether the color grading effect is enabled.
  83205. */
  83206. get: function () {
  83207. return this.imageProcessingConfiguration.colorGradingEnabled;
  83208. },
  83209. /**
  83210. * Gets wether the color grading effect is enabled.
  83211. */
  83212. set: function (value) {
  83213. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83214. },
  83215. enumerable: true,
  83216. configurable: true
  83217. });
  83218. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  83219. /**
  83220. * Gets wether tonemapping is enabled or not.
  83221. */
  83222. get: function () {
  83223. return this._imageProcessingConfiguration.toneMappingEnabled;
  83224. },
  83225. /**
  83226. * Sets wether tonemapping is enabled or not
  83227. */
  83228. set: function (value) {
  83229. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83230. },
  83231. enumerable: true,
  83232. configurable: true
  83233. });
  83234. ;
  83235. ;
  83236. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  83237. /**
  83238. * The camera exposure used on this material.
  83239. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83240. * This corresponds to a photographic exposure.
  83241. */
  83242. get: function () {
  83243. return this._imageProcessingConfiguration.exposure;
  83244. },
  83245. /**
  83246. * The camera exposure used on this material.
  83247. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83248. * This corresponds to a photographic exposure.
  83249. */
  83250. set: function (value) {
  83251. this._imageProcessingConfiguration.exposure = value;
  83252. },
  83253. enumerable: true,
  83254. configurable: true
  83255. });
  83256. ;
  83257. ;
  83258. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  83259. /**
  83260. * Gets The camera contrast used on this material.
  83261. */
  83262. get: function () {
  83263. return this._imageProcessingConfiguration.contrast;
  83264. },
  83265. /**
  83266. * Sets The camera contrast used on this material.
  83267. */
  83268. set: function (value) {
  83269. this._imageProcessingConfiguration.contrast = value;
  83270. },
  83271. enumerable: true,
  83272. configurable: true
  83273. });
  83274. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  83275. /**
  83276. * Gets the Color Grading 2D Lookup Texture.
  83277. */
  83278. get: function () {
  83279. return this._imageProcessingConfiguration.colorGradingTexture;
  83280. },
  83281. /**
  83282. * Sets the Color Grading 2D Lookup Texture.
  83283. */
  83284. set: function (value) {
  83285. this.imageProcessingConfiguration.colorGradingTexture = value;
  83286. },
  83287. enumerable: true,
  83288. configurable: true
  83289. });
  83290. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  83291. /**
  83292. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83293. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83294. * 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;
  83295. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83296. */
  83297. get: function () {
  83298. return this.imageProcessingConfiguration.colorCurves;
  83299. },
  83300. /**
  83301. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83302. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83303. * 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;
  83304. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83305. */
  83306. set: function (value) {
  83307. this.imageProcessingConfiguration.colorCurves = value;
  83308. },
  83309. enumerable: true,
  83310. configurable: true
  83311. });
  83312. /**
  83313. * The entire material has been created in order to prevent overdraw.
  83314. * @returns false
  83315. */
  83316. BackgroundMaterial.prototype.needAlphaTesting = function () {
  83317. return true;
  83318. };
  83319. /**
  83320. * The entire material has been created in order to prevent overdraw.
  83321. * @returns true if blending is enable
  83322. */
  83323. BackgroundMaterial.prototype.needAlphaBlending = function () {
  83324. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  83325. };
  83326. /**
  83327. * Checks wether the material is ready to be rendered for a given mesh.
  83328. * @param mesh The mesh to render
  83329. * @param subMesh The submesh to check against
  83330. * @param useInstances Specify wether or not the material is used with instances
  83331. */
  83332. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83333. var _this = this;
  83334. if (useInstances === void 0) { useInstances = false; }
  83335. if (subMesh.effect && this.isFrozen) {
  83336. if (this._wasPreviouslyReady) {
  83337. return true;
  83338. }
  83339. }
  83340. if (!subMesh._materialDefines) {
  83341. subMesh._materialDefines = new BackgroundMaterialDefines();
  83342. }
  83343. var scene = this.getScene();
  83344. var defines = subMesh._materialDefines;
  83345. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  83346. if (defines._renderId === scene.getRenderId()) {
  83347. return true;
  83348. }
  83349. }
  83350. var engine = scene.getEngine();
  83351. // Lights
  83352. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  83353. defines._needNormals = true;
  83354. // Textures
  83355. if (defines._areTexturesDirty) {
  83356. defines._needUVs = false;
  83357. if (scene.texturesEnabled) {
  83358. if (scene.getEngine().getCaps().textureLOD) {
  83359. defines.TEXTURELODSUPPORT = true;
  83360. }
  83361. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83362. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  83363. return false;
  83364. }
  83365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  83366. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  83367. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  83368. defines.OPACITYFRESNEL = this._opacityFresnel;
  83369. }
  83370. else {
  83371. defines.DIFFUSE = false;
  83372. defines.DIFFUSEHASALPHA = false;
  83373. defines.GAMMADIFFUSE = false;
  83374. defines.OPACITYFRESNEL = false;
  83375. }
  83376. var reflectionTexture = this._reflectionTexture;
  83377. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83378. if (!reflectionTexture.isReadyOrNotBlocking()) {
  83379. return false;
  83380. }
  83381. defines.REFLECTION = true;
  83382. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  83383. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  83384. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  83385. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  83386. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  83387. defines.INVERTCUBICMAP = true;
  83388. }
  83389. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  83390. switch (reflectionTexture.coordinatesMode) {
  83391. case BABYLON.Texture.CUBIC_MODE:
  83392. case BABYLON.Texture.INVCUBIC_MODE:
  83393. defines.REFLECTIONMAP_CUBIC = true;
  83394. break;
  83395. case BABYLON.Texture.EXPLICIT_MODE:
  83396. defines.REFLECTIONMAP_EXPLICIT = true;
  83397. break;
  83398. case BABYLON.Texture.PLANAR_MODE:
  83399. defines.REFLECTIONMAP_PLANAR = true;
  83400. break;
  83401. case BABYLON.Texture.PROJECTION_MODE:
  83402. defines.REFLECTIONMAP_PROJECTION = true;
  83403. break;
  83404. case BABYLON.Texture.SKYBOX_MODE:
  83405. defines.REFLECTIONMAP_SKYBOX = true;
  83406. break;
  83407. case BABYLON.Texture.SPHERICAL_MODE:
  83408. defines.REFLECTIONMAP_SPHERICAL = true;
  83409. break;
  83410. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  83411. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  83412. break;
  83413. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  83414. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  83415. break;
  83416. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  83417. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  83418. break;
  83419. }
  83420. if (this.reflectionFresnel) {
  83421. defines.REFLECTIONFRESNEL = true;
  83422. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  83423. this._reflectionControls.x = this.reflectionAmount;
  83424. this._reflectionControls.y = this.reflectionReflectance0;
  83425. this._reflectionControls.z = this.reflectionReflectance90;
  83426. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  83427. }
  83428. else {
  83429. defines.REFLECTIONFRESNEL = false;
  83430. defines.REFLECTIONFALLOFF = false;
  83431. }
  83432. }
  83433. else {
  83434. defines.REFLECTION = false;
  83435. defines.REFLECTIONFALLOFF = false;
  83436. defines.REFLECTIONBLUR = false;
  83437. defines.REFLECTIONMAP_3D = false;
  83438. defines.REFLECTIONMAP_SPHERICAL = false;
  83439. defines.REFLECTIONMAP_PLANAR = false;
  83440. defines.REFLECTIONMAP_CUBIC = false;
  83441. defines.REFLECTIONMAP_PROJECTION = false;
  83442. defines.REFLECTIONMAP_SKYBOX = false;
  83443. defines.REFLECTIONMAP_EXPLICIT = false;
  83444. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83445. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83446. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83447. defines.INVERTCUBICMAP = false;
  83448. defines.REFLECTIONMAP_OPPOSITEZ = false;
  83449. defines.LODINREFLECTIONALPHA = false;
  83450. defines.GAMMAREFLECTION = false;
  83451. }
  83452. }
  83453. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  83454. defines.USERGBCOLOR = this._useRGBColor;
  83455. defines.NOISE = this._enableNoise;
  83456. }
  83457. if (defines._areImageProcessingDirty) {
  83458. if (!this._imageProcessingConfiguration.isReady()) {
  83459. return false;
  83460. }
  83461. this._imageProcessingConfiguration.prepareDefines(defines);
  83462. }
  83463. // Misc.
  83464. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  83465. // Values that need to be evaluated on every frame
  83466. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  83467. // Attribs
  83468. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  83469. if (mesh) {
  83470. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83471. mesh.createNormals(true);
  83472. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  83473. }
  83474. }
  83475. }
  83476. // Get correct effect
  83477. if (defines.isDirty) {
  83478. defines.markAsProcessed();
  83479. scene.resetCachedMaterial();
  83480. // Fallbacks
  83481. var fallbacks = new BABYLON.EffectFallbacks();
  83482. if (defines.FOG) {
  83483. fallbacks.addFallback(0, "FOG");
  83484. }
  83485. if (defines.POINTSIZE) {
  83486. fallbacks.addFallback(1, "POINTSIZE");
  83487. }
  83488. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  83489. if (defines.NUM_BONE_INFLUENCERS > 0) {
  83490. fallbacks.addCPUSkinningFallback(0, mesh);
  83491. }
  83492. //Attributes
  83493. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83494. if (defines.NORMAL) {
  83495. attribs.push(BABYLON.VertexBuffer.NormalKind);
  83496. }
  83497. if (defines.UV1) {
  83498. attribs.push(BABYLON.VertexBuffer.UVKind);
  83499. }
  83500. if (defines.UV2) {
  83501. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83502. }
  83503. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  83504. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  83505. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  83506. "vFogInfos", "vFogColor", "pointSize",
  83507. "vClipPlane", "mBones",
  83508. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  83509. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  83510. "shadowLevel", "alpha",
  83511. "vBackgroundCenter", "vReflectionControl",
  83512. "vDiffuseInfos", "diffuseMatrix",
  83513. ];
  83514. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  83515. var uniformBuffers = ["Material", "Scene"];
  83516. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  83517. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  83518. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  83519. uniformsNames: uniforms,
  83520. uniformBuffersNames: uniformBuffers,
  83521. samplers: samplers,
  83522. defines: defines,
  83523. maxSimultaneousLights: this._maxSimultaneousLights
  83524. });
  83525. var onCompiled = function (effect) {
  83526. if (_this.onCompiled) {
  83527. _this.onCompiled(effect);
  83528. }
  83529. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  83530. };
  83531. var join = defines.toString();
  83532. subMesh.setEffect(scene.getEngine().createEffect("background", {
  83533. attributes: attribs,
  83534. uniformsNames: uniforms,
  83535. uniformBuffersNames: uniformBuffers,
  83536. samplers: samplers,
  83537. defines: join,
  83538. fallbacks: fallbacks,
  83539. onCompiled: onCompiled,
  83540. onError: this.onError,
  83541. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  83542. }, engine), defines);
  83543. this.buildUniformLayout();
  83544. }
  83545. if (!subMesh.effect || !subMesh.effect.isReady()) {
  83546. return false;
  83547. }
  83548. defines._renderId = scene.getRenderId();
  83549. this._wasPreviouslyReady = true;
  83550. return true;
  83551. };
  83552. /**
  83553. * Build the uniform buffer used in the material.
  83554. */
  83555. BackgroundMaterial.prototype.buildUniformLayout = function () {
  83556. // Order is important !
  83557. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  83558. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  83559. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  83560. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  83561. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  83562. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  83563. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  83564. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  83565. this._uniformBuffer.addUniform("pointSize", 1);
  83566. this._uniformBuffer.addUniform("shadowLevel", 1);
  83567. this._uniformBuffer.addUniform("alpha", 1);
  83568. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  83569. this._uniformBuffer.addUniform("vReflectionControl", 4);
  83570. this._uniformBuffer.create();
  83571. };
  83572. /**
  83573. * Unbind the material.
  83574. */
  83575. BackgroundMaterial.prototype.unbind = function () {
  83576. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  83577. this._uniformBuffer.setTexture("diffuseSampler", null);
  83578. }
  83579. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  83580. this._uniformBuffer.setTexture("reflectionSampler", null);
  83581. }
  83582. _super.prototype.unbind.call(this);
  83583. };
  83584. /**
  83585. * Bind only the world matrix to the material.
  83586. * @param world The world matrix to bind.
  83587. */
  83588. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  83589. this._activeEffect.setMatrix("world", world);
  83590. };
  83591. /**
  83592. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  83593. * @param world The world matrix to bind.
  83594. * @param subMesh The submesh to bind for.
  83595. */
  83596. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  83597. var scene = this.getScene();
  83598. var defines = subMesh._materialDefines;
  83599. if (!defines) {
  83600. return;
  83601. }
  83602. var effect = subMesh.effect;
  83603. if (!effect) {
  83604. return;
  83605. }
  83606. this._activeEffect = effect;
  83607. // Matrices
  83608. this.bindOnlyWorldMatrix(world);
  83609. // Bones
  83610. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  83611. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  83612. if (mustRebind) {
  83613. this._uniformBuffer.bindToEffect(effect, "Material");
  83614. this.bindViewProjection(effect);
  83615. var reflectionTexture = this._reflectionTexture;
  83616. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  83617. // Texture uniforms
  83618. if (scene.texturesEnabled) {
  83619. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83620. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  83621. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  83622. }
  83623. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83624. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  83625. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  83626. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  83627. }
  83628. }
  83629. if (this.shadowLevel > 0) {
  83630. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  83631. }
  83632. this._uniformBuffer.updateFloat("alpha", this.alpha);
  83633. // Point size
  83634. if (this.pointsCloud) {
  83635. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  83636. }
  83637. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  83638. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  83639. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  83640. }
  83641. // Textures
  83642. if (scene.texturesEnabled) {
  83643. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83644. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  83645. }
  83646. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83647. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  83648. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83649. }
  83650. else if (!defines.REFLECTIONBLUR) {
  83651. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83652. }
  83653. else {
  83654. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  83655. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  83656. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  83657. }
  83658. if (defines.REFLECTIONFRESNEL) {
  83659. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  83660. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  83661. }
  83662. }
  83663. }
  83664. // Clip plane
  83665. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  83666. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  83667. }
  83668. if (mustRebind || !this.isFrozen) {
  83669. if (scene.lightsEnabled) {
  83670. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  83671. }
  83672. // View
  83673. this.bindView(effect);
  83674. // Fog
  83675. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83676. // image processing
  83677. this._imageProcessingConfiguration.bind(this._activeEffect);
  83678. }
  83679. this._uniformBuffer.update();
  83680. this._afterBind(mesh);
  83681. };
  83682. /**
  83683. * Dispose the material.
  83684. * @forceDisposeEffect Force disposal of the associated effect.
  83685. * @forceDisposeTextures Force disposal of the associated textures.
  83686. */
  83687. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  83688. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  83689. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  83690. if (forceDisposeTextures) {
  83691. if (this.diffuseTexture) {
  83692. this.diffuseTexture.dispose();
  83693. }
  83694. if (this.reflectionTexture) {
  83695. this.reflectionTexture.dispose();
  83696. }
  83697. }
  83698. this._renderTargets.dispose();
  83699. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83700. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83701. }
  83702. _super.prototype.dispose.call(this, forceDisposeEffect);
  83703. };
  83704. /**
  83705. * Clones the material.
  83706. * @name The cloned name.
  83707. * @returns The cloned material.
  83708. */
  83709. BackgroundMaterial.prototype.clone = function (name) {
  83710. var _this = this;
  83711. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  83712. };
  83713. /**
  83714. * Serializes the current material to its JSON representation.
  83715. * @returns The JSON representation.
  83716. */
  83717. BackgroundMaterial.prototype.serialize = function () {
  83718. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83719. serializationObject.customType = "BABYLON.BackgroundMaterial";
  83720. return serializationObject;
  83721. };
  83722. /**
  83723. * Gets the class name of the material
  83724. * @returns "BackgroundMaterial"
  83725. */
  83726. BackgroundMaterial.prototype.getClassName = function () {
  83727. return "BackgroundMaterial";
  83728. };
  83729. /**
  83730. * Parse a JSON input to create back a background material.
  83731. * @param source
  83732. * @param scene
  83733. * @param rootUrl
  83734. * @returns the instantiated BackgroundMaterial.
  83735. */
  83736. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  83737. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  83738. };
  83739. /**
  83740. * Standard reflectance value at parallel view angle.
  83741. */
  83742. BackgroundMaterial.standardReflectance0 = 0.05;
  83743. /**
  83744. * Standard reflectance value at grazing angle.
  83745. */
  83746. BackgroundMaterial.standardReflectance90 = 0.5;
  83747. __decorate([
  83748. BABYLON.serializeAsColor3()
  83749. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  83750. __decorate([
  83751. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83752. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  83753. __decorate([
  83754. BABYLON.serialize()
  83755. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  83756. __decorate([
  83757. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83758. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  83759. __decorate([
  83760. BABYLON.serializeAsColor3()
  83761. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  83762. __decorate([
  83763. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83764. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  83765. __decorate([
  83766. BABYLON.serialize()
  83767. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  83768. __decorate([
  83769. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83770. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  83771. __decorate([
  83772. BABYLON.serializeAsColor3()
  83773. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  83774. __decorate([
  83775. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83776. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  83777. __decorate([
  83778. BABYLON.serialize()
  83779. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  83780. __decorate([
  83781. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83782. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  83783. __decorate([
  83784. BABYLON.serializeAsTexture()
  83785. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  83786. __decorate([
  83787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83788. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  83789. __decorate([
  83790. BABYLON.serialize()
  83791. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  83792. __decorate([
  83793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83794. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  83795. __decorate([
  83796. BABYLON.serializeAsTexture()
  83797. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  83798. __decorate([
  83799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83800. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  83801. __decorate([
  83802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83803. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  83804. __decorate([
  83805. BABYLON.serialize()
  83806. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  83807. __decorate([
  83808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83809. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  83810. __decorate([
  83811. BABYLON.serialize()
  83812. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  83813. __decorate([
  83814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83815. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  83816. __decorate([
  83817. BABYLON.serializeAsVector3()
  83818. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  83819. __decorate([
  83820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83821. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  83822. __decorate([
  83823. BABYLON.serialize()
  83824. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  83825. __decorate([
  83826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83827. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  83828. __decorate([
  83829. BABYLON.serialize()
  83830. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  83831. __decorate([
  83832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83833. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  83834. __decorate([
  83835. BABYLON.serialize()
  83836. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  83837. __decorate([
  83838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83839. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  83840. __decorate([
  83841. BABYLON.serialize()
  83842. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  83843. __decorate([
  83844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83845. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  83846. __decorate([
  83847. BABYLON.serialize()
  83848. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  83849. __decorate([
  83850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83851. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  83852. __decorate([
  83853. BABYLON.serialize()
  83854. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  83855. __decorate([
  83856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83857. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  83858. __decorate([
  83859. BABYLON.serialize()
  83860. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  83861. __decorate([
  83862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83863. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  83864. __decorate([
  83865. BABYLON.serialize()
  83866. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  83867. __decorate([
  83868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83869. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  83870. __decorate([
  83871. BABYLON.serialize()
  83872. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  83873. __decorate([
  83874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83875. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  83876. __decorate([
  83877. BABYLON.serializeAsImageProcessingConfiguration()
  83878. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  83879. return BackgroundMaterial;
  83880. }(BABYLON.PushMaterial));
  83881. BABYLON.BackgroundMaterial = BackgroundMaterial;
  83882. })(BABYLON || (BABYLON = {}));
  83883. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  83884. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83885. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83886. s = arguments[i];
  83887. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83888. t[p] = s[p];
  83889. }
  83890. return t;
  83891. };
  83892. var BABYLON;
  83893. (function (BABYLON) {
  83894. /**
  83895. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  83896. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  83897. * It also helps with the default setup of your imageProcessing configuration.
  83898. */
  83899. var EnvironmentHelper = /** @class */ (function () {
  83900. /**
  83901. * constructor
  83902. * @param options
  83903. * @param scene The scene to add the material to
  83904. */
  83905. function EnvironmentHelper(options, scene) {
  83906. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  83907. this._scene = scene;
  83908. this._setupBackground();
  83909. this._setupImageProcessing();
  83910. }
  83911. /**
  83912. * Creates the default options for the helper.
  83913. */
  83914. EnvironmentHelper._getDefaultOptions = function () {
  83915. return {
  83916. createGround: true,
  83917. groundSize: 15,
  83918. groundTexture: this._groundTextureCDNUrl,
  83919. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83920. groundOpacity: 0.9,
  83921. enableGroundShadow: true,
  83922. groundShadowLevel: 0.5,
  83923. enableGroundMirror: false,
  83924. groundMirrorSizeRatio: 0.3,
  83925. groundMirrorBlurKernel: 64,
  83926. groundMirrorAmount: 1,
  83927. groundMirrorFresnelWeight: 1,
  83928. groundMirrorFallOffDistance: 0,
  83929. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  83930. groundYBias: 0.00001,
  83931. createSkybox: true,
  83932. skyboxSize: 20,
  83933. skyboxTexture: this._skyboxTextureCDNUrl,
  83934. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  83935. backgroundYRotation: 0,
  83936. sizeAuto: true,
  83937. rootPosition: BABYLON.Vector3.Zero(),
  83938. setupImageProcessing: true,
  83939. environmentTexture: this._environmentTextureCDNUrl,
  83940. cameraExposure: 0.8,
  83941. cameraContrast: 1.2,
  83942. toneMappingEnabled: true,
  83943. };
  83944. };
  83945. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  83946. /**
  83947. * Gets the root mesh created by the helper.
  83948. */
  83949. get: function () {
  83950. return this._rootMesh;
  83951. },
  83952. enumerable: true,
  83953. configurable: true
  83954. });
  83955. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  83956. /**
  83957. * Gets the skybox created by the helper.
  83958. */
  83959. get: function () {
  83960. return this._skybox;
  83961. },
  83962. enumerable: true,
  83963. configurable: true
  83964. });
  83965. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  83966. /**
  83967. * Gets the skybox texture created by the helper.
  83968. */
  83969. get: function () {
  83970. return this._skyboxTexture;
  83971. },
  83972. enumerable: true,
  83973. configurable: true
  83974. });
  83975. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  83976. /**
  83977. * Gets the skybox material created by the helper.
  83978. */
  83979. get: function () {
  83980. return this._skyboxMaterial;
  83981. },
  83982. enumerable: true,
  83983. configurable: true
  83984. });
  83985. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  83986. /**
  83987. * Gets the ground mesh created by the helper.
  83988. */
  83989. get: function () {
  83990. return this._ground;
  83991. },
  83992. enumerable: true,
  83993. configurable: true
  83994. });
  83995. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  83996. /**
  83997. * Gets the ground texture created by the helper.
  83998. */
  83999. get: function () {
  84000. return this._groundTexture;
  84001. },
  84002. enumerable: true,
  84003. configurable: true
  84004. });
  84005. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  84006. /**
  84007. * Gets the ground mirror created by the helper.
  84008. */
  84009. get: function () {
  84010. return this._groundMirror;
  84011. },
  84012. enumerable: true,
  84013. configurable: true
  84014. });
  84015. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  84016. /**
  84017. * Gets the ground mirror render list to helps pushing the meshes
  84018. * you wish in the ground reflection.
  84019. */
  84020. get: function () {
  84021. if (this._groundMirror) {
  84022. return this._groundMirror.renderList;
  84023. }
  84024. return null;
  84025. },
  84026. enumerable: true,
  84027. configurable: true
  84028. });
  84029. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  84030. /**
  84031. * Gets the ground material created by the helper.
  84032. */
  84033. get: function () {
  84034. return this._groundMaterial;
  84035. },
  84036. enumerable: true,
  84037. configurable: true
  84038. });
  84039. /**
  84040. * Updates the background according to the new options
  84041. * @param options
  84042. */
  84043. EnvironmentHelper.prototype.updateOptions = function (options) {
  84044. var newOptions = __assign({}, this._options, options);
  84045. if (this._ground && !newOptions.createGround) {
  84046. this._ground.dispose();
  84047. this._ground = null;
  84048. }
  84049. if (this._groundMaterial && !newOptions.createGround) {
  84050. this._groundMaterial.dispose();
  84051. this._groundMaterial = null;
  84052. }
  84053. if (this._groundTexture) {
  84054. if (this._options.groundTexture != newOptions.groundTexture) {
  84055. this._groundTexture.dispose();
  84056. this._groundTexture = null;
  84057. }
  84058. }
  84059. if (this._skybox && !newOptions.createSkybox) {
  84060. this._skybox.dispose();
  84061. this._skybox = null;
  84062. }
  84063. if (this._skyboxMaterial && !newOptions.createSkybox) {
  84064. this._skyboxMaterial.dispose();
  84065. this._skyboxMaterial = null;
  84066. }
  84067. if (this._skyboxTexture) {
  84068. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  84069. this._skyboxTexture.dispose();
  84070. this._skyboxTexture = null;
  84071. }
  84072. }
  84073. if (this._groundMirror && !newOptions.enableGroundMirror) {
  84074. this._groundMirror.dispose();
  84075. this._groundMirror = null;
  84076. }
  84077. if (this._scene.environmentTexture) {
  84078. if (this._options.environmentTexture != newOptions.environmentTexture) {
  84079. this._scene.environmentTexture.dispose();
  84080. }
  84081. }
  84082. this._options = newOptions;
  84083. this._setupBackground();
  84084. this._setupImageProcessing();
  84085. };
  84086. /**
  84087. * Sets the primary color of all the available elements.
  84088. * @param color
  84089. */
  84090. EnvironmentHelper.prototype.setMainColor = function (color) {
  84091. if (this.groundMaterial) {
  84092. this.groundMaterial.primaryColor = color;
  84093. }
  84094. if (this.skyboxMaterial) {
  84095. this.skyboxMaterial.primaryColor = color;
  84096. }
  84097. if (this.groundMirror) {
  84098. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  84099. }
  84100. };
  84101. /**
  84102. * Setup the image processing according to the specified options.
  84103. */
  84104. EnvironmentHelper.prototype._setupImageProcessing = function () {
  84105. if (this._options.setupImageProcessing) {
  84106. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  84107. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  84108. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  84109. this._setupEnvironmentTexture();
  84110. }
  84111. };
  84112. /**
  84113. * Setup the environment texture according to the specified options.
  84114. */
  84115. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  84116. if (this._scene.environmentTexture) {
  84117. return;
  84118. }
  84119. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  84120. this._scene.environmentTexture = this._options.environmentTexture;
  84121. return;
  84122. }
  84123. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  84124. this._scene.environmentTexture = environmentTexture;
  84125. };
  84126. /**
  84127. * Setup the background according to the specified options.
  84128. */
  84129. EnvironmentHelper.prototype._setupBackground = function () {
  84130. if (!this._rootMesh) {
  84131. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  84132. }
  84133. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  84134. var sceneSize = this._getSceneSize();
  84135. if (this._options.createGround) {
  84136. this._setupGround(sceneSize);
  84137. this._setupGroundMaterial();
  84138. this._setupGroundDiffuseTexture();
  84139. if (this._options.enableGroundMirror) {
  84140. this._setupGroundMirrorTexture(sceneSize);
  84141. }
  84142. this._setupMirrorInGroundMaterial();
  84143. }
  84144. if (this._options.createSkybox) {
  84145. this._setupSkybox(sceneSize);
  84146. this._setupSkyboxMaterial();
  84147. this._setupSkyboxReflectionTexture();
  84148. }
  84149. this._rootMesh.position.x = sceneSize.rootPosition.x;
  84150. this._rootMesh.position.z = sceneSize.rootPosition.z;
  84151. this._rootMesh.position.y = sceneSize.rootPosition.y;
  84152. };
  84153. /**
  84154. * Get the scene sizes according to the setup.
  84155. */
  84156. EnvironmentHelper.prototype._getSceneSize = function () {
  84157. var groundSize = this._options.groundSize;
  84158. var skyboxSize = this._options.skyboxSize;
  84159. var rootPosition = this._options.rootPosition;
  84160. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  84161. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84162. }
  84163. var sceneExtends = this._scene.getWorldExtends();
  84164. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  84165. if (this._options.sizeAuto) {
  84166. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  84167. this._scene.activeCamera.upperRadiusLimit) {
  84168. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  84169. skyboxSize = groundSize;
  84170. }
  84171. var sceneDiagonalLenght = sceneDiagonal.length();
  84172. if (sceneDiagonalLenght > groundSize) {
  84173. groundSize = sceneDiagonalLenght * 2;
  84174. skyboxSize = groundSize;
  84175. }
  84176. // 10 % bigger.
  84177. groundSize *= 1.1;
  84178. skyboxSize *= 1.5;
  84179. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  84180. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  84181. }
  84182. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84183. };
  84184. /**
  84185. * Setup the ground according to the specified options.
  84186. */
  84187. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  84188. var _this = this;
  84189. if (!this._ground) {
  84190. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  84191. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  84192. this._ground.parent = this._rootMesh;
  84193. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  84194. }
  84195. this._ground.receiveShadows = this._options.enableGroundShadow;
  84196. };
  84197. /**
  84198. * Setup the ground material according to the specified options.
  84199. */
  84200. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  84201. if (!this._groundMaterial) {
  84202. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  84203. }
  84204. this._groundMaterial.alpha = this._options.groundOpacity;
  84205. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  84206. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  84207. this._groundMaterial.primaryLevel = 1;
  84208. this._groundMaterial.primaryColor = this._options.groundColor;
  84209. this._groundMaterial.secondaryLevel = 0;
  84210. this._groundMaterial.tertiaryLevel = 0;
  84211. this._groundMaterial.useRGBColor = false;
  84212. this._groundMaterial.enableNoise = true;
  84213. if (this._ground) {
  84214. this._ground.material = this._groundMaterial;
  84215. }
  84216. };
  84217. /**
  84218. * Setup the ground diffuse texture according to the specified options.
  84219. */
  84220. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  84221. if (!this._groundMaterial) {
  84222. return;
  84223. }
  84224. if (this._groundTexture) {
  84225. return;
  84226. }
  84227. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  84228. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  84229. return;
  84230. }
  84231. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  84232. diffuseTexture.gammaSpace = false;
  84233. diffuseTexture.hasAlpha = true;
  84234. this._groundMaterial.diffuseTexture = diffuseTexture;
  84235. };
  84236. /**
  84237. * Setup the ground mirror texture according to the specified options.
  84238. */
  84239. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  84240. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84241. if (!this._groundMirror) {
  84242. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  84243. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  84244. this._groundMirror.anisotropicFilteringLevel = 1;
  84245. this._groundMirror.wrapU = wrapping;
  84246. this._groundMirror.wrapV = wrapping;
  84247. this._groundMirror.gammaSpace = false;
  84248. if (this._groundMirror.renderList) {
  84249. for (var i = 0; i < this._scene.meshes.length; i++) {
  84250. var mesh = this._scene.meshes[i];
  84251. if (mesh !== this._ground &&
  84252. mesh !== this._skybox &&
  84253. mesh !== this._rootMesh) {
  84254. this._groundMirror.renderList.push(mesh);
  84255. }
  84256. }
  84257. }
  84258. }
  84259. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  84260. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  84261. };
  84262. /**
  84263. * Setup the ground to receive the mirror texture.
  84264. */
  84265. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  84266. if (this._groundMaterial) {
  84267. this._groundMaterial.reflectionTexture = this._groundMirror;
  84268. this._groundMaterial.reflectionFresnel = true;
  84269. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  84270. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  84271. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  84272. }
  84273. };
  84274. /**
  84275. * Setup the skybox according to the specified options.
  84276. */
  84277. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  84278. var _this = this;
  84279. if (!this._skybox) {
  84280. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  84281. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  84282. }
  84283. this._skybox.parent = this._rootMesh;
  84284. };
  84285. /**
  84286. * Setup the skybox material according to the specified options.
  84287. */
  84288. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  84289. if (!this._skybox) {
  84290. return;
  84291. }
  84292. if (!this._skyboxMaterial) {
  84293. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  84294. }
  84295. this._skyboxMaterial.useRGBColor = false;
  84296. this._skyboxMaterial.primaryLevel = 1;
  84297. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  84298. this._skyboxMaterial.secondaryLevel = 0;
  84299. this._skyboxMaterial.tertiaryLevel = 0;
  84300. this._skyboxMaterial.enableNoise = true;
  84301. this._skybox.material = this._skyboxMaterial;
  84302. };
  84303. /**
  84304. * Setup the skybox reflection texture according to the specified options.
  84305. */
  84306. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  84307. if (!this._skyboxMaterial) {
  84308. return;
  84309. }
  84310. if (this._skyboxTexture) {
  84311. return;
  84312. }
  84313. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  84314. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84315. return;
  84316. }
  84317. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  84318. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  84319. this._skyboxTexture.gammaSpace = false;
  84320. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84321. };
  84322. /**
  84323. * Dispose all the elements created by the Helper.
  84324. */
  84325. EnvironmentHelper.prototype.dispose = function () {
  84326. if (this._groundMaterial) {
  84327. this._groundMaterial.dispose(true, true);
  84328. }
  84329. if (this._skyboxMaterial) {
  84330. this._skyboxMaterial.dispose(true, true);
  84331. }
  84332. this._rootMesh.dispose(false);
  84333. };
  84334. /**
  84335. * Default ground texture URL.
  84336. */
  84337. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  84338. /**
  84339. * Default skybox texture URL.
  84340. */
  84341. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  84342. /**
  84343. * Default environment texture URL.
  84344. */
  84345. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  84346. return EnvironmentHelper;
  84347. }());
  84348. BABYLON.EnvironmentHelper = EnvironmentHelper;
  84349. })(BABYLON || (BABYLON = {}));
  84350. //# sourceMappingURL=babylon.environmentHelper.js.map
  84351. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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\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>\nvoid main(void) {\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<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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#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\ngl_FragColor=color;\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)\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#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\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\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=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*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(reflectionCoords,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*=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\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\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#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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\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}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \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}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\ngl_FragColor=original;\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);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\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}","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#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{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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}","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);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\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\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\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#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\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\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=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*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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,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,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  84352. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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};\nuniform sampler2D shadowSampler{X};\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#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}\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 SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\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#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;\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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\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\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\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,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,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,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#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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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#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 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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","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;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  84353. globalObject["BABYLON"] = BABYLON;
  84354. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderPass = BABYLON.PostProcessRenderPass;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var HighlightLayer = BABYLON.HighlightLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;
  84355. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderPass,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper };